Simplifying function expressions and the function statement in JavaScript

Read full article on the Infragistics blog

In JavaScript, a function can be created in three possible ways:

  1. Function as an expression
  2. Function as a statement
  3. Arrow functions

In this post, we will learn about function expressions and the function statement.

Consider the following code:


function add(num1, num2) {
return num1 + num2;
}
var res = add(7, 2);
console.log(res);

When you create a function as shown above, it is called a function declaration or statement. You can rewrite the code above to add a function in different ways, as shown below:


var add = function (num1, num2) {
return num1 + num2;
}
var res = add(7, 2);
console.log(res);

The function created above is called a function expression – in this case, an anonymous function expression. A named function expression can be created as below:


var add = function a(num1, num2) {
return num1 + num2;
}
var res = add(7, 2);
console.log(res);

The name of the function expression can only be used inside a function body, which is helpful in recursion. A function expression can either be a:

  1. Named function expression
  2. Anonymous function expression

The third method of creating a function is by using the Arrow function, which was introduced in ECMAScript 6. You can learn more about Arrow functions here.

Read full article on the Infragistics blog


Discover more from Dhananjay Kumar

Subscribe to get the latest posts sent to your email.

Published by Dhananjay Kumar

Dhananjay Kumar is founder of NomadCoder and ng-India

Leave a comment

Discover more from Dhananjay Kumar

Subscribe now to keep reading and get access to the full archive.

Continue reading