Skip to content
Related Articles

Related Articles

JavaScript | Function expression

View Discussion
Improve Article
Save Article
  • Last Updated : 08 Oct, 2021
View Discussion
Improve Article
Save Article

Function Expression  allows us to create an anonymous function which doesn’t have any function name which is the main difference between Function Expression and Function Declaration. A function expression can be used as an IIFE (Immediately Invoked Function Expression)which runs as soon as it is defined. A function expression has to be stored in a variable and can be accessed using variableName.  With the ES6 features introducing Arrow Function, it becomes more easier to declare function expression.

Syntax for Function Declaration: 

function functionName(x, y) { statements... return (z) };

Syntax for Function Expression (anonymous) :  

let variableName = function(x, y) { statements... return (z) };

Syntax for Function Expression (named) :  

let variableName = function functionName(x, y) 
{ statements... return (z) };

Syntax for Arrow Function: 

let variableName = (x, y) => { statements... return (z) }; 

Note: 

  • A function expression has to be defined first before calling it or using it as a parameter.
  • An arrow function must have an return statement.

Below examples illustrate the function expression in JavaScript:

Example 1: Code for Function Declaration.

Javascript




<script>
    function callAdd(x, y){
        let z = x + y;
        return z;   
    }
    console.log("Addition : " + callAdd(7, 4));
</script>

Output: 

Addition : 11

Example 2: Code for Function Expression (anonymous

Javascript




<script>
    var calSub = function(x, y){
        let z = x - y;
        return z;
    }
 
    console.log("Subtraction : " + calSub(7, 4));
 </script>

Output: 

Subtraction : 3

Example 3: Code for Function Expression (named

Javascript




<script>
    var calMul = function Mul(x, y){
        let z = x * y;
        return z;
    }
 
    console.log("Multiplication : " + calMul(7, 4));
</script>

Output: 

Multiplication : 28

Example 4: Code for Arrow Function 

Javascript




<script>
    var calDiv = (x, y) => {
        let z = x / y;
        return z;
    }
 
    console.log("Division : " + calDiv(24, 4));
</script>

Output: 

Division : 6

Supported Browser:

  • Chrome 1 and above
  • Edge 12 and above
  • Firefox 1 and above
  • Internet Explorer 3 and above
  • Opera 3 and above
  • Safari 1 and above

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!