Skip to content

Functions

Preeti Wadhwani edited this page Jun 10, 2021 · 22 revisions

Functions in JS

Functions in JS are objects

Every JavaScript function is actually a Function object. This can be seen with the code (function(){}).constructor === Function, which returns true.

you can check by using console.dir(function_name)

Different ways of creating Functions

The function declaration (function statement) defines a function with the specified parameters.

function helloWorld(){
   console.log("Hello");
}

You can also define functions using function expression.

// function expression

// function without any name is called anonymous function
const sum = function (a, b){
   return a+b;
}

sum(1,2);

or using the Function constructor

As of ES2015, you can also use arrow functions which is compact syntax of traditional function expression

  • If we have one parameter we can skip paranthesis
  • If we have only one statement we can skip curly braces and return keyword
const materials = [
  'Hydrogen',
  'Helium',
  'Lithium',
  'Beryllium'
];

console.log(materials.map(material => material.length));
// expected output: Array [8, 6, 7, 9]

Higher Order Functions

Functions that operate with/on other functions are called higher order function

  • function that can accept other function as arguments
// func here is a callback function, will be called sometime in future and callTwoTimes is higher order functions
function callTwoTimes(func){
 func();
 func();
}

function greet(){
 console.log("Hello Everyone");
}

callTwoTimes(greet);

Output:
Hello Everyone
Hello Everyone
  • function that return a function
function multiplyBy(num){
  // returning anonymous function
  return function(input){
       return input * num;
  }
}

const double = multiplyBy(2);
console.log(double(4));

Output:
8

Built-In HOF

  • map, reduce, filter are some inbuilt array functions which are HOF, as they all accept functions as an argument
  • setTimeout is another example which accept functions and milliseconds as arg

Note: When you don't need to reuse a function then use anonymous function. It is being used when we need to call function only at one place

Clone this wiki locally