Functions in ES6 | ECMAScript 6
Functions in ECMAScript 6
In ECMAScript programming language, the term ‘function’ can be defined as a collection or group of input statements, used to perform particular computational calculations and generate the output according to the given input. A function is a specific block of code created to perform a specific activity. It can be executed when the developer calls or invokes a function.
In other words, we can define a function as a building block of code that is reusable, maintainable, and readable. It means we can reuse, maintain, read, and write the code in an easier manner. In the JavaScript programming language, the functions are also used to perform the operations.
In ECMAScript 6, we can define a function by using the Function keywordwith a function_name and the parentheses (). We can also use letters, digits, underscore, and dollar sign as the function name. It is mandatory to define the function body inside the curly braces {}. The brackets in function name contain the parameter name but separated with comma.
Syntax
Function function_name () { // Body of the function }
Function Invocation
If we force or wants the function to the execution, then it is compulsory to call or invoke it. Here, we have the syntax of function invocation.
Syntax
function_name ()
Here, we have an example of defining the simple function.
Example
Function welcome() // Defining the function { console.log (“welcome function invoked”); } welcome(); // Function invoking
In the above example, welcome() is a function. The curly braces {} shows the body of the functionor the scope of the function.
Output
After the execution of the above code, we will get the following output.
Classification of Function
In ECMAScript, the function can be classified into two following types.
- Parameterized function
- Returning function
Parameterized function
The parameterized function can be defined as the method used to pass the value to the functions. The developer can pass the value to the function at the time of function invocation. It is mandatory that the number of values passed in a function matches the number of function parameters.
Syntax
Here is the syntax of defining a parameterized function.
Function funct_name (parameter 1, parameter 2, ……..parameter N) { // Body of function }
Example
function add (p, q); var a = p + q; { console.log (“p = ” +p); console.log (“q = ” +q); console.log (“p + q = ” +a); }
In the above code, we defined a function add () with two parameters (p, q). After the execution of the code we will get the addition of two parameters in variable a.
Output
The Default function parameters
If the parameter is undefined or we do not pass a value, then the function accesses its default value at the time of initialization.
Example
Function display (a1, a2 = 10) { console.log (“a1 =” +a1); console.log (“a1 =” +a1); } display (20);
In the above code, the parameter a2 has default value 10. Here the function takes 10 as the value of parameter a2.
Output
After the execution of the example, we get the following output.
If we pass the value to the function parameter a2 explicitly, then the default value of the function will be overwritten. We will understand it with an example.
Example
Function display (a1, a2 = 10) { console.log (“a1 =” +a1); console.log (“a1 =” +a1); } display (20, 40);
In the above code, the default value of function parameter a2 will be changed with the newly passed value.
Output
After the execution of the example, we get the following output.
The Rest Parameters
The rest parameter allows us to pass the number of values in a function. It means we can pass a number of values in a function, but all the values must have the same type. In other words, we can define the rest parameter as a procurator for various arguments of the same type.
The declaration of the rest parameter is very easy. We can declare the rest parameter name prefixed with a spread operator that contains three dots (…).
Note: The rest parameter is always last in the function parameter list.
Example
function display (p, …args) { Console.log (p + “ ” + args); } display (10, 20, 30, 40, 50, 60, 70, 80);
Output
Returning function
The returning functions are those functions that return the value to the caller with the help of the return statement. The end or the last part of the returning function is always a return statement. The developer can only use one return statement in the return function, and it is the last statement of the function.
When the ECMAScript compiler influences the return statement, then it stops the execution and exits. It means we can use the return statement to stop the execution of the function immediately.
Syntax
Function function_name () { // code statement to be executed return value; }
Example
function mul (p, q) { return p * q; } var r = mul (25, 10); console.log (r);
In the above code, we defined a function mul () with two parameters (p, q). After the execution of the code, we get the multiplication of two parameters in variable r. The return function returns the resultant value to the caller.
Output
After the execution of the code, we will get the following output.
The Generator Function
ECMAScript programming language provides a new feature of the generator function. It helps us to work with functions and iterators. The ECMAScript generator is also a type of function that provides a facility to pause many times in the middle and can be resumed after.
Anonymous function
The anonymous functions are those functions which do not have any name. It means a function that is not bound to any function name is known as an anonymous function. The anonymous functions are declared at the run time.
The working procedure of the anonymous functions is the same as other standard functions. It means these functions can take input from the user and generate the output accordingly. We cannot access the anonymous function after the initial formation. We can also assign these functions inside a variable.
Syntax
var x = function ( [arguments] ) { // code statement to be executed }
Example
var welcome = function () { console.log (“Hello ECMAScript”); console.log (“Welcome to the world of JavaScript”); } welcome ();
Output
Anonymous Parameterized Function
var anonym = function (x, y) { Return x – y; } Function sub () { var result; result = anonym (500, 300); console.log (“sub:” + result) } Sub ();
Example
After the successful execution of the code, we will get the following output.
We can consider an anonymous function as an argument. It means for the other functions the anonymous function will be an argument. Here, we have an example given below to understand it.
Example
set Sessionout (function () { Console.log (“The session is over”); } 10000); // 10000 millisecond = 10 second
Output
After the execution of the code, we will get the following output.
Arrow Function
The arrow function is a new feature used in ECMAScript 6. This function helps us to write and work with the functions accurately. The arrow functions also make the source code more structured and readable.
Function Hoisting
The term hoisting is a process in which declared functions are moved to the top of the scope before the execution of code statement. We can also perform hoisting with functions like the variables. Unlike the variable hoisting, if we hoist the declared function, then it only hoists the definition of the function instead of the function name.
We will try to understand it with the help of the following example.
Example
welcome (); function welcome () { console.log (“welcome to JavaScript”); }
Output
After the execution of the code, we will get the following output.
In the above example, we called the function before the declaration of the function, but the code still works. We cannot hoist the function expression. Now we are going to understand it by the following example.
Example
hoist_funct (); var hoist_funct () = function () { console.log (“Welcome to ECMAScript”); }
Output
After the execution of the code, we will get the following output.
In the above output, we get a Type error because hoist_funct () is not a function; it is an expression. The expression hoisting is not allowed in ECMAScript 6.
The Function Constructor
The function constructor can be defined as a new way to build a function. It helps us to build the function object. In ECMAScript 6, the function statement is not only a way to determine a new function. We can also determine the new function with the operator by using a function () constructor. The function creation with the help of a function constructor is less valuable then function statement or function expression.
Syntax
var variablename = new funct (args1, args2, …..body of the function);
The syntax of function constructor contains the following parameters.
- Body of the function- The function body includes string arguments. Thefunctionbodyis the last argument of the function, contained arbitrary statements of JavaScript, separated with a semicolon (:).
- Arguments (args1, args2)- These are used as the name of the formal arguments.
Example
var add = new function (‘p’, ‘q’, ‘return p + q’); // A function with the two arguments returns addition of the value console.log (“The sum of the number:” + add(100,250)); // Function calling
Output
After the execution of the code, we will get the following output.
Recursion and JavaScript Function
The Recursive function is concerned to a function which calls itself again and again. The process of recursion is performed by the recursive function. Recursion is a mechanism in which the function calls itself repeatedly until it will get the results. It is a standard method or a way to call the same function with different parameters inside a loop. We will better understand this concept with the help of an example.
Example
function factorial1 (value) { if (value <= 1) { return 1; } else { return value * factorial1 (value - 1); } } console.log(factorial1(4)); console.log(factorial1(3)); console.log(factorial1(2));
Output
When we execute the above code, we will get the following output.
Difference between Function Declaration and Function Expression
Function Declaration | Function Expression |
It can be parsed before the execution. | It can only be parsed if the script engine encounters it during the execution. |
It can be hoisted. | It cannot be hoisted. |
We cannot leave off the function name in it. | We can leave off the name of the function to build the anonymous function. |
Syntax function f1 (args1, args2) { // statements } | Syntax function f2 (args1, args2) { // statements } |