DEV Community

loading...
Cover image for Function Declaration Vs Function Expression in JS

Function Declaration Vs Function Expression in JS

aiman9411 profile image aiman9411 ・2 min read

I stumbled upon this question when learning JavaScript the other day, so I did some reading to understand the differences between those two types of function. I will try to summarise few points that I gathered based on my reading.

Intro to Function Declaration

// Example of Function Declaration 
function multiplyNum(firstNum, secondNum) {
    return firstNum * secondNum;
}
Enter fullscreen mode Exit fullscreen mode

Function declaration declares a function and will be invoked once we call the function. Also, we need to define it using function keyword, followed by name and parentheses {}.

Intro to Function Expression

// Example of Function Expression 
var multiplyNum =  function(firstNum, secondNum) {
    return firstNum * secondNum;
}
Enter fullscreen mode Exit fullscreen mode

Function expression is basically a JavaScript function that is stored in a variable. In the example above, we do not write the function using function keyword first, instead we write it as if we define a variable.

Hoisting

This is subtle yet an important difference between those two functions. When we run the JavaScript file, function declaration will be hoisted to the top of the code before any code is executed. In other words, functions written as function declarations are known before the code is run.

// We can call the function before we declare it
console.log(multiplyNum(1,3))

// Example of Function Declaration 
function multiplyNum(firstNum, secondNum) {
    return firstNum * secondNum;
}
//3
Enter fullscreen mode Exit fullscreen mode

On the other hand, functions written as function expressions are not hoisted when we run the script. An example is when we run the code below, we will encounter an error instead of the value 3.

// When we call the function before we declare it
console.log(addNum(1,4))

// Example of Function Declaration 
var addNum = function(firstNum, secondNum) {
    return firstNum + secondNum;
}
// We will get error message instead of the value 5.
Enter fullscreen mode Exit fullscreen mode

Which One Should We Use?

The answer is it is a matter of personal preference. If you want to call a function before we declare it, then obviously function declaration is the best option. If you want to have a better structure, then you might consider function expression as the answer.

All in all, happy coding and I hope that you have learned something from this post. Cheers!

Discussion

pic
Editor guide