Function expression in JavaScript

A function expression is similar to the declaring function.
There is some difference between function and function expression like you can omit function name in the function expression.


let varName = function [name]([parameters]){
    //function body
}
                    

Let us see the example of a function expression.


let addition = function(operand1, operand2){
    return operand1 + operand2;
}

let result = addition(3,4);
console.log(result);
//output: 7
                    

In the above code, a variable addition is assigned a function. Note that the function which is assigned doesn't have any name. You can add the name though.
Calling the function expression is the same. There is no difference in calling a function.

Why function expression?

You must be wondering that if function expression works like a function, then why do we need function expression?

  • Function dynamic allocation
  • Callback function

Function dynamic allocation

Sometimes you need to create a function according to the result or according to any condition.


let createCars;
let totalCarsSold = 9;
if(totalCarsSold > 10){
    createCars = function(){
        console.log("We need to create more cars");
    };
} else {
    createCars = function(){
        console.log("No more cars need to be created");
    }
}
createCars();
//output: No more cars need to be created
                    

As you can see, using function expression, you can create a function dynamically.
The function expression is created when the execution reaches the line where it is defined and we can use it only after that.

Callback function

A callback function is a function which is passed to the function as a parameter. Let us have a look at an example first.


function isCarNeeded(cb){
    if(typeof(cb) === "function"){
        cb();
    }
}

function yes(){
    console.log("Yes car is needed");
}

isCarNeeded(yes);
//output: Yes car is needed
                    

In above example, yes function is a callback which is passed to isCarNeeded function. Here function is used as a callback.
Most of the times, a callback function is going to be used only once. So function should not be used as a callback. In the above example, we have used a function.
Now let us see anonymous function expression as a callback function.


function isCarNeeded(cb){
    if(typeof(cb) === "function"){
        cb();
    }
}

isCarNeeded(function(){
    console.log("Yes car is needed");
});
//output: Yes car is needed
                    

As you can see, an anonymous function is passed as a callback function. Now, anonymous function is passed which is assigned to cb in isCarNeeded function.

Conclusion

In this section, you learned about function expression and why it is used. The function expression is used regularly by programmers.
In next section, you will learn about the difference between function and function expression in JavaScript.