Arrow functions in JavaScript

Arrow functions were introduced in ES6 (a version of JavaScript). The arrow functions have different syntax for creating JavaScript functions. The arrow function syntax is a bit shorter as it omits function keyword. It also solves problems with this keyword in JavaScript.

Syntax difference between Normal function and Arrow function:

Normal functionArrow function
function someFunction() {
// code
}
const someFunction = () => {
// code
}

Here no arguments are used. But arguments can be hold in ().

You can you arrow functions in the following ways as per your requirements:

  1. Single Argument in arrow function
  2. Multiple Arguments in arrow function
  3. Single Line arrow functions

Single Argument in arrow function:

If you expect only one argument for an arrow function, then you can use like following:

Example:

let greet = (name) => {
    console.log("Hi,", name);
}

greet("John");

Output:

Hi, John

If you are receiving only one argument, then you can omit the parenthesis. Code written above can be written as follows:

let greet = name => {
    console.log("Hi,", name);
}

greet("John");

Multiple Arguments in arrow function:

If you expect multiple arguments for an arrow function, then you can use like following:

Example:

let total = (num1, num2) => {
    console.log(num1 + num2);
}

total(4, 5);

Output:

9

Single Line arrow functions:

You can write a single line arrow function if you have only one line of the function body.

Example:

let total = (num1, num2) => console.log(num1 + num2);

total(4, 5);

Output:

9

If you have problems while implementing code, you can ask me through the comment section.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments