JavaScript: Function expression

Profile picture for user arilio666

A function expression is how we can define a function using the variable name accessed to it and must be always be invoked to be defined, also can be used as IIFE (Immediately invoked function expression). In Ecma script 6 it is much easier, as it introduced the arrow function.

Let's see some of the various expressions!

1. Normal Function Expression

Syntax

function functionName(parameters)
{ 
    //body
}

Example

function square(a)
{
    return a * a;
}
console.log(square(2))

Output: 4

This is a normal function expression created with a function name and invoked with the name of the function likewise.

2. Anonymous Function Expression

Syntax

var func = function(parameters)
{
    //body
}

Example

var squareRoot = function(a)
{
    var b = a * a;
    return b;
}
console.log(squareRoot(44))

Output: 1936

This is the anonymous function expression where a function name is not used and is called with the variable and invoked with it likewise.

3. Named Function Expression

Syntax

var func = function functionName(parameters)
{
    //body
}

Example

var squareRoot2 = function sRoot(a)
{
    var b = a * a;
    return b;
}
console.log(squareRoot2(92))

Output: 8464

This is the named function expression where the function is named and can be accessed with both the variable name and the function name which is set too.

4. Arrow Function

Syntax

var func = (parameters) => {
//body
}

Example

var squareRoot3 = (a) => 
{
    var b = a * a;
    return b;
}
console.log(squareRoot3(33))

Output: 1089

By Ecma Script 6 This is the arrow function that was introduced here we don't need to declare the keyword function instead declare with the => and continue the rest like the old expressions.