Header Responsive Ads

What is function

Function is a separate block of code that may or may not get argument(s), or may or may not return something. It is executed only when it is called. Functions are written to reuse. Write the code once and use it many time.

what is function in javascript

Function Definition

  • Javascript function is defined with keyword "function"
  • Than function name
  • Than comma separated list of parameters inside parentheses. 
  • And finally body of function enclosed with curly braces.

function name(param1, param2)
{
    body
}

In below example, we will write a function that receive radius of circle as parameter, calculate area of circle and return it to caller function.

function calculateArea(r){
    //area = pi*r*r
    let a = 3.14 * r *r
    return a
}

Now call this function as

var area = calculateArea(4)
console.log('Area is: '+area)

Output: Area is: 50.24

Same function return different result based on different parameters.


Local Variable

Parameters of a function become local variable to store passed values to this function. These local variables cannot be accessed outside the called function. Local variables are created when the function is invoked and destroyed when then function ends.


Arrow Function

Arrow function reduce the code and make then function more shorter. It was introduced by ES6.

Traditional Function Vs Arrow Function

Below is the same function written above to calculate area of circle.

var calculateArea = function (r){
    return 3.14 * r *r
}

Now we will make it shorter by converting it to arrow function. First remove keyword "function" and insert => after parentheses.

var calculateArea = (r=>{
    return 3.14 * r *r
}

No need parentheses in case of single parameter

var calculateArea = r =>{
    return 3.14 * r *r
}

Now if there is only one expression, then remove curly braces and return keyword as.

var calculateArea = r => 3.14 * r *r

We have already learnt array functions. You can write arrow functions for array as.

var numbers = [5,1,9,3]
numbers.map((element=> {
    return element*2
})

Similarly you can write arrow functions for sort(), every(), some(), reduce(), filter() etc.


Post a Comment

Previous Post Next Post