FrontendDeveloper.in

ECMAScript question detail

Arrow functions

The arrow functions provides a more concise syntax for writing function expressions by opting out the function and return keywords using fat arrow(=>) notation. Let's see how this arrow function looks like,

// Function Expression
var multiplyFunc = function(a, b) {
return a * b;
}
console.log(multiplyFunc(2, 5)); // 10

// Arrow function
var multiplyArrowFunc = (a, b) => a * b;
console.log(multiplyArrowFunc(2, 5)); // 10

You can also skip parenthesis(()) if the function has exactly one parameter(either zero or more than one parameter). Apart from this, you can wrap braces({}) if the function has more than one expression in the body.

Let's list down all the variations of arrow functions,

//1. Single parameter and single statement
const message = name => console.log("Hello, " + name + "!");
message("Sudheer"); // Hello, Sudheer!

//2. Multiple parameters and single statement
const multiply = (x, y) => x * y;
console.log(multiply(2, 5)); // 10

//3. Single parameter and multiple statements
const even = number => {
if(number%2) {
console.log("Even");
} else {
console.log("Odd");
}
}
even(5); // odd

//4. Multiple parameters and multiple statements
const divide = (x, y) => {
if(y != 0) {
return x / y;
}
}
console.log(divide(100, 5)); // 20

//5. No parameter and single statement
const greet = () => console.log('Hello World!');
greet(); // Hello World!
Back to all ECMAScript questions
Get LinkedIn Premium at Rs 399