ES6 Functions

A function is the set of input statements, which performs specific computations and produces output. It is a block of code that is designed for performing a particular task. It is executed when it gets invoked (or called). Functions allow us to reuse and write the code in an organized way. Functions in JavaScript are used to perform operations.

In JavaScript, functions are defined by using function keyword followed by a name and parentheses (). The function name may include digits, letters, dollar sign, and underscore. The brackets in the function name may consist of the name of parameters separated by commas. The body of the function should be placed within curly braces {}.

The syntax for defining a standard function is as follows:

snippet
function function_name() {
	//body of the function
}

To force the execution of the function, we must have to invoke (or call) the function. It is known as function invocation. The syntax for invoking a function is as follows:

snippet
function_name()

Example

snippet
function hello() //defining a function
{
   console.log ("hello function called");
   }
hello(); //calling of function

In the above code, we have defined a function hello(). The pair of parentheses {} define the body of the function, which is called a scope of function.

Output

Output
hello function called

Let us try to understand different functions.

Parameterized functions

Parameters are the names that are listed in the definition of the function. They are the mechanism of passing the values to functions.

The values of the parameters are passed to the function during invocation. Unless it is specified explicitly, the number of values passed to a function must match with the defined number of parameters.

Syntax

The syntax for defining a parameterized function is:

snippet
function function_name( parameter1,parameter2 ,…..parameterN) {   
   	 //body of the function
}

Example

In this example of parameterized function, we are defining a function mul(), which accepts two parameters x and y, and it returns their multiplication in the result. The parameter values are passed to the function during invocation.

snippet
function mul( x , y) { 
    var c = x * y;
    console.log("x = "+x);
    console.log("y = "+y);
    console.log("x * y = "+c); 
 } 
mul(20,30);

Output

Output
x = 20 y = 30 x * y = 600

Default Function Parameters

In ES6, the function allows the initialization of parameters with default values if the parameter is undefined or no value is passed to it.

You can see the illustration for the same in the following code:

For example

snippet
function show (num1, num2=200) 
{
    console.log("num1 = " +num1);
    console.log("num2 = " +num2);

}
show(100);

In the above function, the value of num2 is set to 200 by default. The function will always consider 200 as the value of num2 if no value of num2 is explicitly passed.

Output

Output
100 200

The default value of the parameter 'num2' will get overwritten if the function passes its value explicitly. You can understand it by using the following example:

For example

snippet
function show(num1, num2=200) 
{
    console.log("num1 = " +num1);
    console.log("num2 = " +num2);
}
show(100,500);

Output

Output
100 500

Rest Parameters

Rest parameters do not restrict you to pass the number of values in a function, but all the passed values must be of the same type. We can also say that rest parameters act as the placeholders for multiple arguments of the same type.

For declaring the rest parameter, the name of the parameter should be prefixed with the spread operator that has three periods (not more than three or not less than three).

You can see the illustration for the same in the following example:

snippet
function show(a, ...args)
{
    console.log(a + " " + args);
}
show(50,60,70,80,90,100);

Output

Output
50,60,70,80,90,100

Note: The rest parameters should be at last in the list of function parameters.

Returning functions

The function also returns the value to the caller by using the return statement. These functions are known as Returning functions. A returning function should always end with a return statement. There can be only one return statement in a function, and the return statement should be the last statement in the function.

When JavaScript reaches the return statement, the function stops the execution and exits immediately. That's why you can use the return statement to stop the execution of the function immediately.

Syntax

A function can return the value by using the return statement, followed by a value or an expression. The syntax for the returning function is as follows:

snippet
function function_name() { 
    //code to be executed
    return value; 
}

Example

snippet
function add( a, b )
{
    return a+b;
}
var sum = add(10,20);
console.log(sum);

In the above example, we are defining a function add() that has two parameters a and b. This function returns the addition of the arguments to the caller.

You will get the following output after the execution of the above code.

Output

Output
30

Generator functions

Generator (or Generator function) is the new concept introduced in ES6. It provides you a new way of working with iterators and functions.

ES6 generator is a different kind of function that may be paused in the middle either one or many times and can be resumed later.

You can learn more about the generator functions by clicking on this link ES6 Generators.

Anonymous function

An anonymous function can be defined as a function without a name. The anonymous function does not bind with an identifier. It can be declared dynamically at runtime. The anonymous function is not accessible after its initial creation.

An anonymous function can be assigned within a variable. Such expression is referred to as function expression. The syntax for the anonymous function is as follows.

Syntax

snippet
var y = function( [arguments] ) 
{ 
     //code to be executed
}

Example

snippet
var hello = function() {
   console.log('Hello World');  
   console.log('I am an anonymous function'); 
 }
 hello();

Output

Output
Hello World I am an anonymous function

Anonymous function as an argument

One common use of the anonymous function is that it can be used as an argument to other functions.

Example

Use as an argument to other function.

snippet
setTimeout(function() 
{
   console.log('Hello World');
 }, 2000);

When you execute the above code, it will show you the output after two seconds.

Output

Output
Hello World

Parameterized Anonymous function

Example

snippet
var anon = function(a,b)
{ 
   return a+b 
}
function sum() { 
   var res; 
   res = anon(100,200); 
   console.log("Sum: "+res)  
} 
sum()

Output

Output
Sum: 300

Arrow functions

Arrow functions are introduced in ES6, which provides you a more accurate way to write the functions in JavaScript. They allow us to write smaller function syntax. Arrow functions make your code more readable and structured.

You can learn more about the arrow functions by clicking on this link ES6 Arrow Function.

Function Hoisting

As variable hoisting, we can perform the hoisting in functions. Unlike the variable hoisting, when function declarations get hoisted, it only hoists the function definition instead of just hoisting the name of the function.

Let us try to illustrate the function hoisting in JavaScript by using the following example:

Example

In this example, we call the function before writing it. Let's see what happens when we call the function before writing it.

snippet
hello();
function hello() {
  console.log("Hello world ");
}

Output

Output
Hello world

In the above code, we have called the function first before writing it, but the code still works.

However, function expressions cannot be hoisted. Let us try to see the illustration of hoisting the function expressions in the following example.

snippet
hello();

var hello = function() {
  console.log("Hello world ");
}

When you execute the above code, you will get a "TypeError: hello is not a function." It happens because function expressions cannot be hoisted.

Output

Output
TypeError: hello is not a function

The Function Constructor

It is the way of defining a new function. The function statement is not the single way to define a new function; we can also dynamically define the function by using the Function() constructor along with the new operator.

It is less efficient than declaring a function using a function expression or function statement.

Syntax

The syntax of creating the function by using the Function() constructor.

snippet
var variable_name = new Function(arg1, arg2..., "Body of the Function");

Parameters used

Its syntax includes:

arg1, arg2, … argN: These are the names that are used by the function as the name of the formal arguments. Each argument must be a string that corresponds to a valid identifier of JavaScript.

Function Body: It is a string that contains the statements of JavaScript comprises the function definition.

It can include any number of string arguments. The last argument is the body of the function, which can contain arbitrary statements of JavaScript, which is separated from each other by semicolons.

The function() constructor does not pass any argument that specifies a name for the function it creates.

Example

snippet
// creating a function that takes two arguments and returns the product of both arguments
var mul = new Function('a', 'b', 'return a * b');

// calling of function
console.log("The product of the numbers is: " +mul(5, 5));

Output

Output
The product of the numbers is: 25

Immediately Invoked Function Expression (IIFE)

It is a function in JavaScript that runs as soon as it is defined. An IIFE (Immediately Invoked Function Expression) can be used for avoiding the variable hoisting from within the blocks. It allows the public access to methods while retaining the privacy for variables defined in the function.

You can learn more about the IIFEs by clicking on this link Immediately Invoked Function Expression (IIFE)

JavaScript Functions and Recursion

When a function calls itself, then it is known as a recursive function. Recursion is a technique to iterate over an operation by having a function call itself repeatedly until it reaches a result.

It is the best way when we require to call the same function regularly with different parameters in a loop.

Example

snippet
function fact(num) {
      if (num <= 1) {
          return 1;
      } else {
          return num * fact(num - 1);
      }
  } 
  console.log(fact(6));
  console.log(fact(5));
  console.log(fact(4));

Output

Output
720 120 24

Function Expression v/s Function Declaration

The fundamental difference between both of them is that the function declarations are parsed before the execution, but the function expressions are parsed only when the script engine encounters it during the execution.

Unlike the function declarations, function expressions in JavaScript do not hoists. You cannot use the function expressions before defining them.

The main difference between a function declaration and function expression is the name of the function, which can be omitted in the function expressions for creating the anonymous functions.

Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents