JavaScript

Arrow functions in JavaScript

Arrow functions were initiated with ES6 as a new syntax for writing JavaScript functions. They save developers time and simplify the scope of functions. Let’s look at the evolution of function syntaxes in JavaScript.
 

Regular function:
function sayHello() {
   return "Hello World!";
}

 

Function with ES5:
sayHello = function() {
  return "Hello World!";
}

 

Function with ES6:
sayHello = () => "Hello World!";

 

 

What is an arrow function?

Arrow functions have a more concise syntax for writing functions. They use => which looks like an arrow. Arrow functions are anonymous functions.

Arrow functions make our code more concise and simplify the scope of functions. These are single-line functions that work much like Lambdas in other languages like Java or Python. By using arrow functions, we avoid having to type the keyword function, return, and the braces {} (are implicit in arrow functions).
 

Example:

If you have parameters, you pass them in parentheses:

sum = (n1 , n2) => n1 + n2;

sum(1, 2); // 3
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *