Created
July 22, 2016 17:27
-
-
Save xandkar/6355b32bf9f5ea42353191d856cde41f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/env node | |
var foo = function() { | |
console.log("foo's x: %s BEFORE IT ENTERS SCOPE", x); | |
x = "xb"; | |
y = "ya"; | |
return 0 | |
} | |
var main = function() { | |
x = "xa"; | |
console.log("main's x1: %s", x); | |
foo(); | |
console.log("main's x2: %s", x); | |
console.log("main's y: %s, WHICH IT HAS NEVER SEEN BEFORE", y); | |
} | |
main() |
#! /usr/bin/env node
var foo = function() {
console.log("foo's x: %s BEFORE IT ENTERS SCOPE", x);
var x = "xb";
var y = "ya";
return 0
}
var main = function() {
x = "xa";
console.log("main's x1: %s", x);
foo();
console.log("main's x2: %s", x);
console.log("main's y: %s, WHICH IT HAS NEVER SEEN BEFORE", y);
}
main()
this is possible because you are in non strict mode.
And because of this, x
and y
are attached to the global scope.
if you test console.log(global.x)
and console.log(global.y)
you may find the same result.
non-strict mode is a nightmare because of scope leaks like this.
And this is the same with this
.
Meaning: with node, always activate strict mode. With browsers, if you don't depend on IE 8, activate it as well.
http://caniuse.com/#search=strict%20mode
@rehia @AeroNotix: Yep. See the gist about loops, which includes output of versions with and without "use strict": https://gist.github.com/xandkar/9a422ea5cf01408a9d67fa4800e53b25
:)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is a very easy to make mistake, especially in loops: https://gist.github.com/xandkar/9a422ea5cf01408a9d67fa4800e53b25