I'm learning about functions in Javascript but getting confused about the use of function declaration and function expression.
Let's say I have the following code:
function callFunction(fn) {
fn();
}
// function expression
var sayHello1 = function() {
console.log("Hello World!");
}
// function declaration
function sayHello2() {
console.log("Hello World!");
}
callFunction(sayHello1); // Hello World!
callFunction(sayHello2); // Hello World!
We can easily see that when passing sayHello1
(function expression) and sayHello2
(function declaration) into callFunction(fn)
, both generate the same output Hello World!
.
Is there any real case that I must use only function declaration/ function expression or I can use them interchangeably all the time?
Thanks so much!