3

It occurred to me, that I have no idea what the scope of

var foo='bar', 
baz = 'bar';

is.

Obviously foo is locally scoped, but is the var keyword necessary on baz to scope it locally, or is my example already locally scoped?

Alex
  • 5,674
  • 7
  • 42
  • 65
  • Looks as a duplicate of http://stackoverflow.com/questions/1470488/difference-between-using-var-and-not-using-var-in-javascript – yadutaf Jul 17 '12 at 18:36

2 Answers2

4

They will both end up in the same scope.

var foo = 'bar', 
    baz = 'bar';

Is just short for:

var foo = 'bar'; 
var baz = 'bar';

So within a function for instance, both foo and baz will become local variables, even if you only declare var once.

Tools like JSLint actually expect the var keyword to be used only once, so if you want to comply with that, you should use the first example.

Christofer Eliasson
  • 32,939
  • 7
  • 74
  • 103
1

This is a very interesting question, indeed. JavaScript is full of border cases.

In this blog post: http://scribu.net/blog/javascript-var-keyword-for-php-developers.html, The authors gives some examples of the impact of using or not the 'var' keyword.

To make a long story short,

  • non declared variables are global
  • declared variables are local, it allows to "override" a global variable.
yadutaf
  • 6,840
  • 1
  • 37
  • 48
  • 1
    There's a comma ater bar... Not a semicolon. – jahroy Jul 17 '12 at 18:43
  • http://bonsaiden.github.com/JavaScript-Garden/#function.scopes is so much more fun for linking people to scope explanations :D (atleast partly because the sidebar is so gorgeous) – Alex Jul 17 '12 at 18:48