Skip to content

Instantly share code, notes, and snippets.

@stephenjfox
Last active November 25, 2022 12:35
Show Gist options
  • Save stephenjfox/fec4c72c7f6ae254f31407295dc72074 to your computer and use it in GitHub Desktop.
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 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
/*
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