Skip to content

Instantly share code, notes, and snippets.

@worldofprasanna
Last active March 13, 2016 05:40
Show Gist options
  • Save worldofprasanna/a223bf0dd4194dc7e37f to your computer and use it in GitHub Desktop.
Save worldofprasanna/a223bf0dd4194dc7e37f to your computer and use it in GitHub Desktop.
Hoisting Issue
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