JavaScript : Functions

JavaScript : Functions

A block of statements.

The function is a defined block containing a set of statements. We can call functions, to execute statements within it. Functions are useful when we have some set of statements to be executed multiple times at different places in the program.

Additionally, functions can take inputs, called function arguments, and can return some value too. Functions that return values are called returning functions and those not are called non-returning functions.

How to define a function?

  1. Using function declaration syntax.

    Example: We want to declare a function that returns double the input value.

     // function is keyword in javascript
    
     function double(input){         // double is name of function
         return input*2;
     }
    
     let x = 2;          
     let y = double(x); // 4
    
  2. Using function expression syntax.

     // functions without name are also called anononymus functions.
     // doubleFunction is variable holding reference to function.
    
     let doubleFunction = function (input){                     
         return input*2;
     }
    
     let x = 2;          
     let y = doubleFunction(x); // 4
    

    Optionally, We can name the function as well in the above syntax.

    
     // doubleFunction is variable holding reference to function.
     // and double is name of function, can be accessed only inside 
     // function definition.
    
     let doubleFunction = function double(input){                     
         return input*2;
     }
    
     let x = 2;          
     let y = doubleFunction(x); // 4
    

    Both function declarations and function expressions are the same, except for two main differences,

    • In function expression syntax, the function name is optional but in the case of function declaration syntax, it is compulsory.

    • In function expression syntax, the function definition is not hoisted to the beginning of the scope but in the case of function declaration, it is.

The most common use cases of function expressions are

  • To pass it as an argument to another function.

  • To return another function from a function.

  • To use as an Immediately invoked function expression( IIFE )

  1. Using arrow function syntax.

     // doubleFunction is variable holding reference to arrow function.
    
     let doubleFunction = (input) => {                     
         return input*2;
     }
    
     let x = 2;          
     let y = doubleFunction(x); // 4
    

    It is a shorter syntax for function expressions but with certain limitations,

    • The arrow function does not have their own this, argument and should not be used as a method.

    • We cannot use the arrow function as a constructor.