Skip to content

Instantly share code, notes, and snippets.

@alexshelkov
Last active February 3, 2022 15:36
Show Gist options
  • Save alexshelkov/43c6af36a0c7deffb6097d81cedd3505 to your computer and use it in GitHub Desktop.
Save alexshelkov/43c6af36a0c7deffb6097d81cedd3505 to your computer and use it in GitHub Desktop.
// file scope
console.log(a); // you may be surprised, but this works and logs undefined
// this is because of the hoisting of definitions
// on top of the nearest function
var a = 1;
console.log(a);
function f1() { // f1 scope
console.log(a); // this is ok -- functions have access to parent scope
console.log(b); // works the same way as with 'a'
var b = 1;
console.log(b);
// TODO: try uncomment
// console.log(x);
// this will throw an error: 'ReferenceError: x is not defined',
// because x() defined in f2 scope
}
function f2() { // f2 scope
console.log(x()); // hoisting help us here because
// function definition is moved to the top of f2
function x() {
console.log('x');
}
console.log(x());
// TODO: try uncomment
// console.log(b);
// this will throw an error: 'ReferenceError: b is not defined',
// because 'b' defined in f1 scope
}
f1();
f2();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment