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 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 arguments, 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 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 single line arrow function, if you have only one line of 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.

Leave a Reply

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