Javascript Tutorial
Javascript Tutorial Introduction to Javascript JavaScript Code Editors & IDE JavaScript Hello World Example Javascript Syntax and Rules syntax_rules javascript_identifiers JavaScript Keywords & Reserved Words javascript_variables JavaScript Const JavaScript let vs var vs const Data Types in JavaScript JavaScript String Template Literals & String interpolation in JavaScript Tagged Templates in JavaScript String to Number in JavaScript Number Data Type in JavaScript NaN in JavaScript JavaScript Number Min & Max & Safe Values JavaScript EPSILON & Floating point precision Infinity in JavaScript JavaScript Bigint BigInt Vs Number in JavaScript Boolean Data Type in JavaScript Undefined in JavaScript Null in JavaScript Null vs Undefined in JavaScript JavaScript Operators Arithmetic Operators in JavaScript Unary plus & minus operators in JavaScript Increment & Decrement Operators in JavaScript Comparison or Relational operators in JavaScript Strict Equality (==) Loose Equality (===) in JavaScript Ternary Conditional Operator in JavaScript Logical Operators in JavaScript Bitwise Operators in JavaScript Assignment Operators in JavaScript Nullish Coalescing Operator in JavaScript Comma Operator in JavaScript Typeof JavaScript Operator Precedence in JavaScript JavaScript if, else & nested if statement Switch Statement in JavaScript While & Do While Loops in JavaScript For Loop in JavaScript Break statement in JavaScript Continue Statement in JavaScript Arrays in JavaScript Array Constructor in Javascript Sparse Array Vs Dense Array in JavaScript How to merge Arrays in JavaScript Array Methods in JavaScript Functions in JavaScript Function Parameters & Arguments in JavaScript JavaScript Default Parameters Pass by Value and Pass by Reference in Javascript Function Expression in Javascript Nested Functions in JavaScript Immediately-invoked Function Expressions (IIFE) JavaScript Callback Functions Arrow Functions in JavaScript Arguments Object In JavaScript Rest Parameters in JavaScript Objects in Javascript Create Objects in JavaScript JavaScript Object Properties Computed Property Names in JavaScript Object Literal in JavaScript Constructor Function & New Operator in JavaScript Delete Operator in JavaScript hasOwnProperty in JavaScript Using Getters and Setters in Javascript DefineProperty in JavaScript JavaScript Property Descriptors Enumerable, Writable & Configurable Object Destructuring in JavaScript Variable Scope in JavaScript Hoisting in JavaScript Lexical Scope & Closures in JavaScript This in JavaScript Global Object, Window & Globalthis in JavaScript Call function in Javascript Prototype In Javascript Prototype Inheritance in JavaScript Instanceof Operator in JavaScript Spread Operator in JavaScript

Function Expression in in Javascript

The Function Expression is another way to create a JavaScript function. We learned how to create JavaScript Function. In that article, we used the Function Statement or declaration to create the Function. In this tutorial, we will look at Function Expression.

Function Expression

Here we create the function as part of the JavaScript Expression.

JavaScript Expression is any code that JavaScript evaluates to get a Value. They produce value

The following is the example, we create a function and assign it to the variable calcArea. We use the variable calcArea to invoke the function

                            
let calcArea = function (width, height) {
    let result = width * height;
    return result;
};
 
 
var result = calcArea(10, 10)
 
console.log(result)
                            
                        
                            
                        

Function Expression Vs Function Declaration

There are a few differences between the Function expression and Function Declaration.

Syntax

If we declare a function using a JavaScript statement, then we call it a Function declaration.

The following code creates the calcArea function using the Function statement/ declaration. Here we give a name to function calcArea. The JavaScript creates a Variable calcArea and assigns the function to it.

Example

                            
function calcArea (width, height) {
    let result = width * height;
    return result;
};
 
                            
                        
                            
                        

If the function is created using a JavaScript expression, then we call it Function Expression

The following is the function expression. We create the function and use the assignment operator to assign it to a variable. Note that we have not given any name to the function. The Syntax of creating the function is almost similar to the function declaration

                            
let calcArea = function (width, height) {
    let result = width * height;
    return result;
};                        
                        
                            
                        

Hoisting

JavaScript process the Function declarations (Hoisting), before it executes any code block. Hence they are available everywhere. But it evaluates the Function Expressions during the code execution and when the code reaches it. Hence they are available only after the evaluation.

JavaScript process all the declaration statements before it executes a block of code. This is called Hoisting.

In the following example, we invoke the calcArea function before its declaration. It works because JavaScript moves the calcArea to the top. Hence It does not matter where we declare the function.

                            
var result = calcArea(10,10)
console.log(result)
 
 
function calcArea (width, height) {
    let result = width * height;
    return result;
};
                            
                        
                            
                        

But the following code results in an error. That is because the hoisting works only in declarations and not in assignments. Since we used the assignment operator to assign the function to the calcArea variable, we can only invoke after the assignment.

                            
var result = calcArea(10,10)  //Uncaught ReferenceError: calcArea is not defined
console.log(result)
 
 
calcArea = function  (width, height) {
    let result = width * height;
    return result;
};                        
                        
                            
                        

Named Function Expression

Hoisting

JavaScript process the Function declarations (Hoisting), before it executes any code block. Hence they are available everywhere. But it evaluates the Function Expressions during the code execution and when the code reaches it. Hence they are available only after the evaluation.

JavaScript process all the declaration statements before it executes a block of code. This is called Hoisting.

In the following example, we invoke the calcArea function before its declaration. It works because JavaScript moves the calcArea to the top. Hence It does not matter where we declare the function.

    
var result = calcArea(10,10)
console.log(result)


function calcArea (width, height) {
let result = width * height;
return result;
};
    

    

But the following code results in an error. That is because the hoisting works only in declarations and not in assignments. Since we used the assignment operator to assign the function to the calcArea variable, we can only invoke after the assignment.

    
var result = calcArea(10,10)  //Uncaught ReferenceError: calcArea is not defined
console.log(result)


calcArea = function  (width, height) {
let result = width * height;
return result;
};                        

    

Consider this example

                            
let calcArea = function areaCalculator(width, height) {
  let result = width * height;
  return result;
};
 
 
calcArea(10,10)  //ok
 
areaCalculator(10,10) //error
                            
                        
                            
                        

Use case of Function Expression

Using it as callback

The callback functions are one of the use cases for a function expression. A callback is a function that we pass as an argument to another function.

For Example, take a look at this function. The third parameter to addNum is a function.The function invokes it with the result. The addNum is not aware of what this function does.

The logToConsole function prints the message to console whatever it gets.

We invoke the addNum with logToConsole as the third argument. You will see the result on the console.

    
function addNum(a, b, callBack) {
    let result = a + b
    callBack(result)
    return result;
}
 
 
function logToConsole(message) {
    console.log(message)
}
 
 
addNum(1, 2, logToConsole)
    

    

Here the logToControl is the callback function. We pass it to the addNum and it invokes it.

We can rewrite the function as shown below. Instead of declaring the function, we use the function expression to create the function on the fly and pass it to the addNum function.

    
function addNum(a, b, callBack) {
    let result = a + b
    callBack(result)
    return result;
}
 
 
addNum(1, 2, function(message) { console.log(message) })                       

    

Advantageous of this is that the function is discarded after it is invoked.

Immediately Invoked Function Expressions (IIFE)

We can create a function using the function expression on the fly, invoke it, and forget about it. Such a use case is called IIFE (Immediately Invoked Function Expressions). It also helps to avoid polluting the global scope.