JavaScript | Function expression

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) };

Syantax 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 funcion expression in JavaScript:

Example 1: Code for Function Declaration.

Javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output: 

Addition : 11

Example 2: Code for Function Expression (anonymous

Javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output: 

Subtration : 3

Example 3: Code for Function Expression (named

Javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output: 

Multiplication : 28

Example 4: Code for Arrow Function 

Javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output: 

Division : 6

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.