Logo

Developer learning path

JavaScript

Arrow functions in JavaScript

Arrow functions

93

#description

Arrow functions are a new feature introduced in ECMAScript 6 (ES6) that provide an alternative way to define functions in JavaScript. They are a shorter and more concise syntax for writing functions than the traditional function syntax.

The basic syntax for an arrow function is:

                    
(param1, param2,, paramN) => { statements }
                  

Here, (param1, param2, …, paramN) are the function parameters, and { statements } is the function body.

If the function body consists of a single expression, you can omit the curly braces and return keyword like this:

                    
(param1, param2,, paramN) => expression
                  

Arrow functions have some notable differences from traditional functions.

  1. Arrow functions don't have their own this value. They inherit the this value from the surrounding code block. This makes it easier to access the correct this value inside functions nested inside other functions.
  1. Arrow functions are always anonymous. You can assign them to a variable or pass them as a parameter to another function, but you can't use them to declare named functions.
  1. Arrow functions can't be used as constructor functions. They don't have a prototype property and can't be used with the new keyword.
  1. Arrow functions can't be used to define methods inside objects. This is because they don't have their own this values, so they can't reference other properties or methods of the object.

Here is an example of a traditional function and an arrow function that do the same thing:

                    
// traditional function
function sum(a, b) {
  return a + b;
}

// arrow function
const sum = (a, b) => a + b;
                  

In this example, the arrow function is shorter and more concise than the traditional function. You don't need to use the return keyword or curly braces in the arrow function because the function body consists of a single expression.

March 25, 2023

If you don't quite understand a paragraph in the lecture, just click on it and you can ask questions about it.

If you don't understand the whole question, click on the buttons below to get a new version of the explanation, practical examples, or to critique the question itself.