Functions in javaScript

Supriya

Functions

A block of code which is defined once but called at a later time.

Some functions can be defined and called at the same time.

  • function declaration
  • function call

Function Declaration

  • function declaration
  • function expression
  • IIFE (immediately invokable function expression)

function declaration

function fName( arg1, arg2, ...)

{

        statement-1;

        statement-2;

        statement-3;

}

function greetTheUser(user)
{
    if(user === undefined)
    {
        user = "new user";
    }
    return (`Hello ${user}, welcome to Target`);
}

// function call

greetTheUser(); 

greetTheUser("james");

function expressions

let fName = function ( arg1, arg2, ...)

{

        statement-1;

        statement-2;

        statement-3;

};

let greetTheUser = function(user)
{
    if(user === undefined)
    {
        user = "new user";
    }
    return (`Hello ${user}, welcome to Target`);
};

// function call

greetTheUser();

greetTheUser("audrey");

IIFE

(function (arg1, arg2, ....)

{      

        statement-1;

        statement-2;

        statement-3;

})();

(function(user)
{
    if(user === undefined)
    {
        user = "new user";
    }
    return (`Hello ${user}, welcome to Target`);
})(); // function call

Arrow Functions

(param1, param2, . . . ) => {

statement-1;

statement-2;

statement-3

. . .

}

Arrow Functions

function funName (user)
{
    if(user === undefined)
    {
        user = "new user";
    }
    return (`Hello ${user}, welcome to Target`);
}; // function defination

funName("bennie") // function call
const funName = (user) => {
    if(user === undefined)
    {
        user = "new user";
    }
    return (`Hello ${user}, welcome to Target`);
}	// function defination

funName("bennie"); // function call

Time to put those brain cells to work


let numList = [45,67,67,78,45,34,23,23,2312,7];
let sum = 0;

const cube = function(num)
            {
                return Math.pow(num,3);
            };

const add = function(num1, num2)
            {
                return num1+num2;
            };

let cubeNum = cube(add(34,45));

// Here comes the tough one....
numList.forEach(function(n){ return sum = sum + n ; });

(function(numAry, cube)
{
numAry.forEach(function(num, i)
    {
        console.log(`${num}is the current value\n`);
    });
console.log(cube);
})(numList, cube);

QUEST!!

We can put the function inside the objects

Hint: { lists and dictionaries } 

Property methods

reduce() method

That previous sum of the array can be done in a single line of code, but this time using the current and the next value.

Hint: { lists } 

Functions in javaScript

By Supriya kotturu

Functions in javaScript

  • 60