Hi guys, I'm reading a JavaScript book and came across this example, but it doesn't fully explain when to use each and what the usecases are other than the fact that named functions are hoisted?
Can someone explain if one is better than the other all the time or what the usecases for each are?
function fun() {
Console.log("Hello from func 1"
}
var fun = function(){
Console.log("Hello from func 2"
}
Both can be used as callbacks etc, to me assigning a variable to a function seems just like a named function? Thanks!
Sorry for lack of formatting, wrote this on my phone. Also couldn't seem to add the image via mobile?
Top comments (4)
The distinction goes a bit deeper than your two examples. MDN provides a good explanation, but I'll give a quick overview:
There are function declarations:
Function declarations must be named.
There are named function expressions:
And there are anonymous function expressions:
As far as I understand, the way you write functions is largely a style choice.
The main differences are:
Of course you can also use the variable name (fibN in this example) to make the function recursive.
hoisting will happen only for named function, not for variable function
Hey Rahul, I mentioned that in the post but what does this actually help with? I understand hoisting (I believe) but surely decently written code wouldn't rely on hoisting anyways?
Most code doesn't need to rely on it, but it's not unusual to see code that does.
The simplest example of it's usefulness is that it lets you sort your functions by name instead of by what each of them depends on, which is helpful for finding code quickly.
It also lets you do cyclical recursion (that is, two or more functions that from a recursive loop), which is impossible without some form of hoisting, forward-declaration, or multi-pass parsing.