Javascript Variable Hoisting not Behaving as Expected in Scratchpad

68 Views Asked by At

I am following the Mozilla developers Javascript tutorial and there is a segment on variable hosting. The tutorial at one point mentions using Firefox's Scratchpad in order to edit javascript to quickly save and see code run.

The code i used (copy paste from tutorial) is:

/**
 * Example 1
 */
console.log(x === undefined); // true
var x = 3;

/**
 * Example 2
 */
// will return a value of undefined
var myvar = 'my value';

(function() {
  console.log(myvar); // undefined
  var myvar = 'local value';
})();

However console.log(x === undefined) returns false. And if I run console.log(x); instead it actually returns 3. console.log(myvar); below returns undefined as expected.

I'm confused as what is supposed to be happening here, is the documentation possibly incorrect/outdated or does Scratchpad interpret this code differently from standard JavaScript, and if so why? I tried to run in a .js file and I get results as expected.

1

There are 1 best solutions below

0
On BEST ANSWER

In the Immediate function, you redeclared the myvar variable in:

(function() {
  console.log(myvar); // undefined
  var myvar = 'local value';
})();

So the global myvar variable from the window scope will be hoisted that's why it returns undefined in console.log(myvar);.

In the other hand if you replace it with console.log(x);, it will print 3 because you haven't redeclared the x variable.

Your problem:

And for the first console.log(x === undefined); statement, it will return false only if you reexecute it, so maybe in your case it was executed twice.