Created
October 10, 2011 00:02
-
-
Save hughfdjackson/1274397 to your computer and use it in GitHub Desktop.
scope craziness
This file contains 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
// ON the behaviour of 'var'less variable declaration | |
// if you do this: | |
function foo(){ | |
age = 99 | |
} | |
foo() | |
console.log(age) | |
// age => 99, because, if age does not yet exist in the global scope, a 'varless' age inside foo implies it into existence | |
//-------------RESET----------------// | |
// if you do this: | |
function foo(){ | |
var age = 99 | |
} | |
foo() | |
console.log(age) | |
// age => reference error, because there is no such var as age in the global scope | |
//-------------RESET----------------// | |
// ON the behaviour of variable hoisting | |
console.log(age) | |
// age => ReferenceError, it's not defined in the global scope | |
//-------------RESET----------------// | |
var age | |
console.log(age) | |
// age => undefined, it's been declared, but nothing's been assigned to it, so it's automatically assigned undefined | |
//-------------RESET----------------// | |
console.log(age) | |
// age => undefined, because of some weird behaviour. When you define a variable (i.e. var age = 99, below), it happens in two parts. First, JS hoists (hence the term) the declaration to the top of the scope (i.e. above console.log(age), just after the reset) and assigns undefined to it. When it gets to the line var age = 99, it assigns 99 to it. | |
var age = 99 | |
console.log(age) | |
// age => 99, because it's been defined now |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment