Last active
March 13, 2016 05:40
-
-
Save worldofprasanna/a223bf0dd4194dc7e37f to your computer and use it in GitHub Desktop.
Hoisting Issue
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
function printName(isFirstName){ | |
console.log(firstName); // Variables hoisted to the top | |
console.log(lastName); | |
if (isFirstName){ | |
var firstName = 'Prasanna'; | |
}else { | |
var lastName = 'V' | |
} | |
} | |
printName(true); | |
/* Output : | |
undefined | |
undefined | |
*/ | |
//------- Safe hoisting ----- | |
function printNameSafely(isFirstName){ | |
console.log(firstName); // Variables are not hoisted to the top | |
console.log(lastName); | |
if (isFirstName){ | |
console.log(firstName); // Still variables are hoisted within the block | |
let firstName = 'Prasanna'; | |
}else { | |
let lastName = 'V' | |
} | |
} | |
printNameSafely(true); | |
/* Output : | |
"ReferenceError: firstName is not defined | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment