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.
In the Immediate function, you redeclared the
myvar
variable in:So the global
myvar
variable from thewindow
scope will be hoisted that's why it returnsundefined
inconsole.log(myvar);
.In the other hand if you replace it with
console.log(x);
, it will print3
because you haven't redeclared thex
variable.Your problem:
And for the first
console.log(x === undefined);
statement, it will returnfalse
only if you reexecute it, so maybe in your case it was executed twice.