Skip to content

11 Functions

Biswajit Sundara edited this page May 1, 2023 · 1 revision

Java Script functions really help in achieving code re usability and ensuring modular design approach.

Java script functions can be categorized in five ways

  1. Anonymous function
  2. Regular function
  3. Function expression
  4. New function
  5. Arrow function

Anonymous Function

Anonymous function is the java script function that doesn't have a name.

  • This is not recommended for regular use.
  • The syntax of the function is function(){}

Used as Callback function

  • This is useful when we pass a function as an argument to another function
setTimeout(function () {  
    console.log('Execute later after 1 second')  
}, 1000);  

Self Invoking Functions

  • Self invoking functions are anonymous functions and it doesn't require any calls to execute the function
  • These are immediately invoked function
  • It doesn't pollute the global scope and forgotten immediately after the execution.
(function () {
    console.log('Hello');
  })();

Regular function

Regular function is the default way of writing the functions and is recommended to use.

Basic function

Function starts with keyword function and followed by function name

function display(){
    console.log('Hello');
}

using the function name we can call it

display();

Functions with arguments

function add(a,b){
    return a+b;
}

x=add(2,3);

console.log(x);

Function Expression

When the function is assigned to a constant/variable, it's called function expression.

  • We can have named or anonymous function expression
  • Declared functions are hoisted but function expressions are not hoisted
  • The declared functions will be available to the entire application
  • However function expressions are available to the code below its initialization.

Anonymous Function Expression

const sum = function(a,b) {
    return a+b;
}

console.log(sum(2,3));

Named Function Expression

const sum = function add(a,b) {
    return a+b;
}

console.log(sum(2,3));

New Function

Java script has a built in function constructor Function()

let addnum= new Function("a","b","return a+b");

console.log(addnum(4,5));

It depends on the situation to create the functions this way. Usually functions are created other ways.

Clone this wiki locally