WebFX WebBoard
Message Thread:
View All Messages
Back to WebFX
 When is var keyword nedded, Anders Both, November 3, 2003
     Re:When is var keyword nedded , Tim Scarfe, November 4, 2003
     Re:When is var keyword nedded, Jeffrey Jangli, November 3, 2003

Subject: Re:When is var keyword nedded From: Tim Scarfe Date: November 4, 2003

Hello Anders

Similar to languages like C# and C++ the "var" keyword is used for setting the scope of the variable. JS implements a "Function" level scope, unlike languages like C# which are far more granular with "Block level" i.e. Structures like for, while, try-catch have scope boundaries.

Think of "var" as meaning "variant". The same way in C# you would do this:

public void hello( ) {
 int iTim=1000;

In JS you do this:

function hello( ) {
 var iTim=1000;

JS doesn't support specific data types, so we just use hungarian notation with the "i" to try to make it as clear as possible, even though we are using a variant.

If you do NOT use the var keyword, the (forgiving) JS engine will simply set it at top scope for you. Here are a couple of examples:

function test( ) {
 iNum=1; // no var so set at top scope
print( iNum ); // it's 1!

function test2( ) {
 var iNum2=1;
print( iNum2 ); // nothing... :)

Other caviats to realise is that JS will always look at your vars first, and will not regard the lexical ordering of them. So this is interesting:

print( tim );
var tim=2;

In this case, the JS engine has initilized the tim variable, but NOT assigned a value. i.e. it's treated like this:

var tim;

Anyway, I could ramble on for hours. For soe more great information - I suggest you check out http://blogs.gotdotnet.com/ericli/ or some of Erik's source code on his components :)


From: Anders Both
Sent: November 3, 2003
Subject: Re:When is var keyword nedded

When declaring your variables you should always use the var keyword

From: Anders Both
Sent: November 3, 2003
Subject: Re:When is var keyword nedded

When is the var keyword nedded. Like you can write

var i=4;i++;

Or just


But you cannot always remove the var keyword.







Enter your reply to this message below. HTML tags are not supported but words that start with http://, ftp:// or mailto: are converted to links.

View All Messages
Back to WebFX