Function in JavaScript

Function is a set of code, that is defined once and can be called n number of times. A function can be reused, thus they are also used to avoid repetition of code. Function comes under reference type. Variables declared inside functions are local variables. Thus they can be used only within same function, not outside function.

typeof operator can check datatype of function.

Function can be both Use Defined and Pre-defined.

javascript functions

JavaScript functions are first-class objects. Means they are very powerful in javascript as compared to other programming languages. They are even more powerful than objects.

Why JavaScript Functions are first class objects?

  1. Functions can be assigned to variables.
  2. Functions can have properties and methods.
  3. Functions can return functions.
  4. Functions can have callbacks.

Functions can be easily reused. To invoke a function, we can use events like click, hover, submit, focus, mousemove etc, or just call by function name followed by parentheses. For exp, if function name is myFunction, use myFunction() to call or invoke function.


JavaScript Function Example

Function Declaration


<script>
    function add(){ 
          // code inside
    } 
</script>

Function Expression


<script>
   var myfunction=function(){ 
   // code inside 
   };
</script>


Function Declarations

Function declaration is the most commonly used method to declare functions in Javascript. A function keyword is started and followed by function name, then parentheses () and then code written inside curly brackets {}. Here is an example.

How to declare function in javascript


        function function_name(){
        
        }
        

Call a function

To call or invoke a function, use function name followed by Parenthesis, i.e. ( ). For example, if function name is sayHi, use sayHi(). We can call a declared function after or before declaration. They are also known as named function.

Function declaration example


<script>    
        sayHello()      // will work
        
    function sayhello(){
            alert("Hello there")
    }
    
        sayHello()      // will work
</script>       

<button onclick="sayHello()">Click</button>       
        

Function Expression

Another way to create function is function expression. In function expression, a variable is declared and then assigned a anonymous function, as it does not have a name. They are not named functions, as they are stored inside a variable.

Function Expression are only invoked after function. If we call a function expression before, an error will occur (function_name is not defined).


<script>         
    good_bye()     // will not work
    var good_bye=function(){
        alert("Good Bye")
        };
    good_bye()     // will work
</script>  
<button onclick="good_bye()">Click</button>               
        

Call a function on button click.

To call a function on button click, use the example below. In first example, a function is created on button click. In Second example, an already build function ( myFunction) is invoked on button click. As function is used inside another function (addEventListener), no need to use parentheses.

Call a function using onclick attribute


<script> 
    function sayHi(){
    alert("Hi");
    }
<script>  
<button onclick="sayHi()">Say Hi</button>            
        

Expression functions are first created and then invoked. If we call an expression function before, an error will occur. Also semicolon is required after function expression.

Arrow Functions

Arrow functions are actually short form of expression functions. To call arrow functions, we have to declare function first and then call.

Arrow functions were introduced in ES6. Its recommended to use function declaration or expression for IE browsers.


    var myFunc1=(x,y)=>{ };    // 2 parameters
    
    var myFunc2=(x)=>{ };        // 1 parameter
    
    var myFunc3=x=>{ };        // 1 parameter

One main difference between arrow function and expression is use of this keyword.


this keyword

this keyword in Javascript refers to current object. In a function, this keyword value depends upon how the function is called. For any function, this keyword is window object, but in strict mode, this keyword is undefined. See example below

Window {parent: Window, opener: null, top: Window, length: 6, frames: Window, …}


    function sayHi(){ 
        console.log(this);        
    }
    sayHi()

<body></body>


    document.body.onclick=function(){ 
        console.log(this);        
    }
    // click on body to call function

undefined

"use strict";
    function sayHi(){ 
        console.log(this);        
    }
    sayHi()

In expression function, this keyword refers to current object. But in arrow function, it is window object. For such cases, avoid using arrow functions for events.

Window {parent: Window, opener: null, top: Window, length: 6, frames: Window, …}


    document.body.onclick=()=>{ 
        console.log(this);        
    }
    // click on body to call function


Return value

Every function returns a value. The default return value is undefined. return operator is used to get a custom value in return when function is called or invoked. This could be a string, number, function, array or object.

Function returns undefined


function sayHi(){
    var x="Hello";
}
sayHi();         // return undefined

Function returns string


function sayHi(){
    return "hello";
}
sayHi();         // return "hello"

Function returns function

Function can also returns a function. See example


function sayHi(){
    return function(){ return "hi"};
}
sayHi();           // return function
sayHi()();         // return "hi"

typeof function and return value

typeof function is "function" , but typeof function() is datatype of return value.


typeof mean;                     // datatype of function
typeof mean();                   // datatype of return value
       

Parameters and Arguments

A Function can have parameters. Default parameter of a function is undefined. While declaration, they are called parameters, but when function is invoked, they are arguments.

Parameters are used to provide changeable values to function for reuse.

Difference between parameters and arguments


function mean(x,y,z){
    var sum =x+y+z;             // x, y and z are parameters
    var a=sum/3;
    return a;
}
        
var i=mean(1,2,9);           // 1,2,9 are arguments, and i is 4          
var j=mean(2,3,4);           // 2,3,4 are arguments, and i is 3 
     

Function Properties

Functions are first class objects in javascript, means they have both properties and methods. These properties are same for function declaration and expression functions.

function.name

Return name of function. The name of function is always string.

Function Name Property


    function area1(){}
    var area2=function(){}; 
    var area3=function area4(){}; 
                                
    area1.name             // returns "area1"
    area2.name             // returns "area2"
    area3.name             // returns "area4"

function.length

Return total no of parameters used in function.

Function length Property


    function area1(x,y){ }
    function area2(x,y,z){ }
    
    area1.length         // return 2
    area2.length         // return 3

custom property

Apart from length and name, functions can have custom properties and methods.


    function user(){ }
    
    user.brandname="Tech Altum";
    user.location="Noida";
    user.year=2012;
    user.getAge=function(){ return 2019-user.year };
    
    user.name                 // return "user"
    
    user.brandname            // return "Tech Altum"
    user.location             // return "Noida"
    user.year                 // return 2012
    
    user.getAge()             // return 7

Its better to use JavaScript Objects to declare properties and methods instead of functions. See example


var user={
            "name":"user",
            "year":2012,
            "location":"Noida"
        }

Immediate Invoke Function

Immediate Invoke Function or self invoking function are anonymous function who call themself. They are not assigned and named. That's why they are anonymous. But they call themself on pageload or event.

Immediate Invoke Function Example


    (function(){
        // statement Statement
    }());
        

Immediate Invoke Function with parameters


    (function(x){
        console.log("Hello", x )
    }("user"));