Created
July 14, 2021 16:34
-
-
Save jameswomack/8c765a3a57090a281cdfc57918973b5e to your computer and use it in GitHub Desktop.
Looking at the difference between function & block scope in JavaScript
This file contains hidden or 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
const console = require("console"); | |
(function () { | |
console.log(foo); // undefined | |
{ | |
var foo = 'foo'; | |
} | |
})(); | |
(function () { | |
{ | |
var foo = 'foo'; | |
} | |
console.log(foo); // foo | |
})(); | |
try { | |
(function () { | |
{ | |
let foo = 'foo'; | |
} | |
console.log(foo); // foo is not defined | |
})(); | |
} catch (e) { | |
console.error(e.message); | |
} | |
try { | |
(function () { | |
console.log(foo); // Cannot access 'foo' before initialization | |
let foo = 'foo'; | |
})(); | |
} catch (e) { | |
console.error(e.message); | |
} | |
try { | |
function logFoo () { | |
console.log(foo); // foo | |
} | |
let foo = 'foo'; | |
logFoo(); | |
} catch (e) { | |
console.error(e.message); | |
} | |
try { | |
function logFoo () { | |
console.log(foo); // foo | |
} | |
process.nextTick(logFoo); | |
let foo = 'foo'; | |
} catch (e) { | |
console.error(e.message); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment