1

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.

Beep
  • 23
  • 3
  • 1
    The console will implicitly use the current page's global scope (the `window`), so once you've defined `x` it stays defined. You could wrap all that code in a big immediately-executed function to make sure you start off with a clean context. – Pointy Nov 27 '17 at 15:50
  • Did you maybe run the example code twice? Then `x` would have already been initialised with `3` on the second (and all subsequent) runs. – Bergi Nov 27 '17 at 16:04
  • But why would re-running the code save the previous variable. Should the 'memory' not get cleared as .js script is running again? Or does this only occur during a complete refresh of the page? – Beep Nov 27 '17 at 17:28

1 Answers1

0

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.

cнŝdk
  • 31,391
  • 7
  • 56
  • 78