-1

I wonder why the two code snipped below generate two different results as in reference below the two have to be the same as were are in global scope and placing var would not make a difference.

I was under the impression due to what explained below and the Javascript hoisting the two generate same output, but don't! why?

What is the purpose of the var keyword and when to use it (or omit it)?

console.log(a)
var a = 90;
// undefined

vs

console.log(a)
a = 90; // no var keyword
// Uncaught ReferenceError: a is not defined
Waterfr Villa
  • 1,217
  • 1
  • 10
  • 33
  • 3
    Hoisting is about how *variable declarations* are treated. The second example doesn't contain a variable declaration but an *assignment*. `var a = 42;` and `a = 42;` are two different very operations: https://astexplorer.net/#/gist/aa885eb9965b58e9c54b0a4a9e39e6c1/13cefb8e4b0ab104f85737d86e6d3afdf7c93209 . – Felix Kling Jun 28 '17 at 23:21

1 Answers1

2

When you put var keyword, what it does is it moves the var part as a declaration on that scope and makes it undefined. In the first case, with var:

console.log(a)
var a = 90;
// undefined

Gets rewritten as:

var a = undefined;
console.log(a)
a = 90;
// undefined

So, you get the undefined here, vs. your second case has it the same way, where there's no declaration or key in window object named a. Hope this is understandable.

The point here is, when you use a var keyword, immediately that's defined as undefined at the top of the scope before anything.

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252