Skip to content

Instantly share code, notes, and snippets.

@xandkar
Created July 22, 2016 17:27
Show Gist options
  • Save xandkar/6355b32bf9f5ea42353191d856cde41f to your computer and use it in GitHub Desktop.
Save xandkar/6355b32bf9f5ea42353191d856cde41f to your computer and use it in GitHub Desktop.
#! /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()
@xandkar
Copy link
Author

xandkar commented Jul 22, 2016

$ ./broken_scope.js
main's x1: xa
foo's x: xa BEFORE IT ENTERS SCOPE
main's x2: xb
main's y: ya, WHICH IT HAS NEVER SEEN BEFORE

This is a very easy to make mistake, especially in loops: https://gist.github.com/xandkar/9a422ea5cf01408a9d67fa4800e53b25

@AeroNotix
Copy link

#! /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()

@rehia
Copy link

rehia commented Jul 22, 2016

this is possible because you are in non strict mode.
And because of this, xand 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

@xandkar
Copy link
Author

xandkar commented Jul 22, 2016

@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