Learn everything about Functions in JavaScript

Functions are an important part of programming and is supported by JavaScript. It enables us to structure our code better and reuse particular parts for tasks. In JavaScript, functions are same as objects and behaves a bit different than in other languages.

In this article, you will:

  • learn to use functions in JavaScript
  • How to pass functions as parameters or assign them to variables?
  • Different types of functions like callback and arrow

In JavaScript, a function definition consists of the function keyword, followed by:

  • The name of the function.
  • A list of parameters to the function, enclosed in parentheses.
  • The definition of the function, enclosed in curly brackets, { }.
  • Functions always return a value. In JavaScript, if no return value is specified, the function will return undefined.
  • Functions are objects.
  • Functions can also return arrays.

Syntax

The syntax of a JavaScript function is as follows:

function functionName(Parameter1, Parameter2, ..)
{
    // Function body
}

Function Call

Calling Functions: After defining a function, the next step is to call them to use it. We can call a function by using the function name separated by the value of parameters enclosed between parenthesis and a semicolon at the end.

Example

function myFunction(p1, p2) {
  return p1 * p2;   //returns the product of p1 and p2
}

Nested Function

  • Here is a simple nested function!
function addSquares(a, b) {
  function square(x) {
    return x * x;
  }
  return square(a) + square(b);
}
a = addSquares(2, 3); // returns 13
b = addSquares(3, 4); // returns 25
c = addSquares(4, 5); // returns 41

Functions with no Return Type

In JavaScript, if no return value is specified, the function will return undefined.

function test(){};
test();    // undefined

Parameters vs. Arguments

  • Parameters are used when defining a function, they are the names created in the function definition. In fact, during a function definition, we can pass in up to 255 parameters! Parameters are separated by commas in the ().

  • Arguments, on the other hand, are the values the function receives from each parameter when the function is executed (invoked).

Return Statement

Another important rule of the return statement is that it stops function execution immediately. Consider this example where we have two return statements in our test function:

function test(){
  return true;
  return false;
};
test();
// true

Function Objects in JavaScript

Functions are function objects. In JavaScript, anything that is not a primitive type ( undefined, null,boolean, number, or string) is an object. Because of this, we can even pass a function as a parameter into another function.

When a function accepts another function as a parameter, or returns a function, it is called a higher order function.

How to pass functions as parameters to another function?

Following is the example of passing functions as parameters to another function:

function func1() {
  console.log("I am 1");
}
function func2() {
  console.log("I am 2");
}
function chose(type, type1, type2) {
  if(type === '1') {
    type1();
  } else if(type === '2') {
    type2();
  }
}
chose('2', func1, func2);

How to assign functions to variable?

In this example, we are assigning a function to a variable.

const square = function(x) {
  return x * x;
}
// prints 25
square(5); 

Arrow Function

An arrow function expression is a syntactically compact alternative to a regular function expression.

Syntax

(param1, param2, …, paramN) => { statements } 
var materials = [
  'Hydrogen',
  'Helium',
  'Lithium',
  'Beryllium'
];
console.log(materials.map(material => material.length));
// expected output: Array [8, 6, 7, 9]

Callback Functions in JavaScript

  • This method of passing in functions to other functions to use them inside is used in JavaScript libraries almost everywhere.

  • The common name for the function passed in is a callback function.

function functionOne(x) { return x; };
function functionTwo(var1) {
    // some code
}
functionTwo(functionOne);
function first(){
  
// Simulate a code delay
  setTimeout( function(){
    
console.log(1);
  }, 500 );
}
function second(){
  console.log(2);
}
first();
second();
// 2
// 1
  • JavaScript didn’t wait for a response from first() before moving on to execute second().

  • Callbacks are a way to make sure certain code doesn’t execute until other code has already finished execution.

Reference


This is a companion discussion topic for the original entry at http://iq.opengenus.org/functions-in-javascript/