1

I'm currently try to learn the basics of JavaScript.

What I understood so far (and please correct me if I'm wrong somewhere): The language differentiates only between global and function scope.

Within functions you have to use the var-keyword when declaring function-wide variables. Otherwise you declare a global variable automatically.

But when I'm in the global space anyway:

Is it necessary to use the var-keyword there too?

I mean: I declare a global variable anyway.

So does it make sense to use var there too? And in case of so: Which sense?

ts248
  • 311
  • 1
  • 4
  • 11

2 Answers2

3

A little experiment:

window.a = 1; // define global variable 'a'

console.log(a); // 1

delete a; // true

console.log(a); // ReferenceError: a is not defined

Everything is ok. But let define a global variable with var keyword:

var a = 1; // define a global variable 'a'

console.log(a); // 1

delete a; // false

console.log(a); // 1, 'a' still exists

If global variable a was created with var, it cannot be deleted.

Read more

Community
  • 1
  • 1
Ali Mamedov
  • 5,116
  • 3
  • 33
  • 47
  • 1
    To be honest, I haven't seen `delete` used in actual code in ages or ever. – John Dvorak May 01 '16 at 11:04
  • @JanDvorak Me too :) – Ali Mamedov May 01 '16 at 11:05
  • @AliMamedov When I get that right: After you have declared a variable in the global space there is no chance to get rid of it anymore? Within a function the life-time is limited until the function ends. But within the global space it would exist to theoretically forever. – ts248 May 01 '16 at 11:10
  • @ts248 If you will declare it with `var` in the global space there is no chance to delete It. But if you will declare It **without** `var` keyword you can easily delete It. – Ali Mamedov May 01 '16 at 11:14
  • 1
    @AliMamedow Got it ! :) Thanks a lot. – ts248 May 01 '16 at 11:16
2

Javascript variables declared in the global scope without var keyword will be attached to the window object. As such they are candidates for deletion (and memory cleanup).

If you want to declare a global variable (which is bad) it's therefore better to attach it explicitly to the window object (and it will emphasize the fact that variable is global).

It's even better to put it in a global object which will take the role of a name space and protect your variable from being overriden by another script.

Regis Portalez
  • 4,675
  • 1
  • 29
  • 41