Last active
November 25, 2022 12:35
-
-
Save stephenjfox/fec4c72c7f6ae254f31407295dc72074 to your computer and use it in GitHub Desktop.
const vs function declaration, showing why you must declare your work first
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
/* | |
This shows that, because of block-scoping, const function references must be | |
invoked in-order or else things will fail silently. | |
const's are added the name space serially (in the order in which they appear) | |
and much of the body isn't declared when we first try to invoke or functions | |
*/ | |
const tryDoTheThing = () => { | |
console.log(`This is me trying to be awesome ${getAwesome()}`) | |
} | |
// "getAwesome is not defined", because it is referenced too early | |
tryDoTheThing() // comment to see the rest work | |
const getAwesome = () => (+((Math.random() * 10000).toString().split('.')[0])) | |
const doTheThing = () => { | |
console.log(`This is awesome! ${getAwesome()}`) | |
} | |
doTheThing() // prints |
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 declarations are given two passes, where the first lifts them to | |
the top of the namespace, allowing "out of order" usage | |
*/ | |
doTheThing(); | |
function doTheThing() { | |
console.log(`This is awesome number ${getAwesome()}`) | |
} | |
function getAwesome() { | |
return (+((Math.random() * 10000).toString().split('.')[0])) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment