Skip to content

Instantly share code, notes, and snippets.

@zakmandhro
Last active January 17, 2022 16:45
Show Gist options
  • Save zakmandhro/ea980963ab85c4b07236c944a0405deb to your computer and use it in GitHub Desktop.
Save zakmandhro/ea980963ab85c4b07236c944a0405deb to your computer and use it in GitHub Desktop.
Show the difference in methods use to namespace functions in const
const WithFunc = {
description: "Hello",
classicFunction() {
console.log(this.description, "description") // works but can lead to 'this' confusion
return "classicFunction"
}
}
const WithConst = {
description: "Hello",
arrowFunction: () => {
console.log(WithConst.description, "description") // need to reference const
return "arrowFunction"
}
}
console.log(classicFunction()) // this works
function classicFunction() {
return "classicFunction"
}
// this doesn't works; const not initialized yet
// console.log(arrowFunction())
// but this works fine because when it's called, arrowFunction is initialized
// this would be the case if this module was exported
const useArrowFunction = () => arrowFunction()
const arrowFunction = () => {
return "arrowFunction"
}
console.log(useArrowFunction())
@zakmandhro
Copy link
Author

zakmandhro commented Jan 17, 2022

One advantage of using function on line 19 is that it gets hoisted to top. A forward reference will work:

oldSchoolFunction("Hello");

function oldSchoolFunction(msg) {
  console.log(msg)
}

The same will not work for const arrow function:

arrowFunction("Hello"); // throws not found

const arrowFunction = (msg) =>  console.log(msg)

However, if arrowFunction is called from another const or function (which is typically how you'd do it) then it's fine.

@zakmandhro
Copy link
Author

You can try this code out on typescriptlang.org

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment