Node JS

Node JS Tutorial - Function Expressions


Video Thumbnail

In this tutorial, we will learn about function expressions in JavaScript. A JavaScript function can be defined using an expression, which can be stored in a variable. After a function expression has been stored in a variable, the variable can be used as a function.

Creating a Function Expression

Let's create a function expression. Go to your project and inside the index.js file, remove all the existing lines and create a variable. Let's say the variable name is `message`. Inside this message variable, assign a function by typing:


var message = function(){ 
    return `Hello World!`; 
}

This is a function expression, where the function name is omitted. Now, let's call this message variable like a function:


console.log(message()); 

Let's run this code. Go to the command prompt and type:


node index.js

You can see the output `Hello World`.

Using Function Expressions as Arguments

We can also use function expressions as arguments. Let's see an example. Create another expression function:


var sum= function(a,b) 
{ 
    return a+b; 
}

This is a sum expression function that returns the sum of two numbers.

Now, create another function that uses a function as a parameter:


var calculateSum = function(fun) 
{ 
    return fun(); 
}

Call this calculate sum function and pass the sum function as an argument:


calculateSum(sum(5,6)); 

Let's check the result, and you can see the output 11.

In this way, you can create and use function expressions in Node.js.

Written by Surfside Media

Senior Full Stack Developer specializing in Web Technologies.