question regarding functions in js
What is the difference between assigning a variable to a function and vice versa?
3 Replies
Do you have a specific example in mind? That question is not very intuitive: you can assign a function to a variable (that's what variables are for - storing values) but you cannot assign a variable to a function.
i meant: what is the difference between assigning a variable to a function and not assigning a variable to a function
Do you mean the difference between
and
?
If so, the difference is hoisting. When you use the
function
keyword the function is "hoisted" to the top of the stack. Normally JS files are read from top to bottom. Meaning you need to declare a variable or function before it's used, but a hoisted function can be used before it's declared.
A function assigned to a variable is not hoisted, so it can't be used before it's declared. But on the flip side, if you declare the function using const
you won't be able to accidentally overwrite the function later.
Any function declared using the function
keyword is mutable: it can be changed to another function or even a non-function variable! Because of this, I much prefer to declare all my functions using const
and putting them at the top of my JS file.
I've had too many situations where I thought I was coming up with a new function name but was overwriting an existing function (or overwriting a function with a variable!). So I don't take any chances anymore and just const
all the things.