JavaScript(JS) Arrow Function
Arrow functions, introduced in ES6 (ECMAScript 2015), are a new syntax for creating functions in JavaScript that offer a shorter and more concise way of writing function expressions.
Here's an example of a traditional function expression:
var double = function(x) { return x * 2; };
And here's an example of the same function expressed as an arrow function:
var double = (x) => { return x * 2; };
Arrow functions have a more concise syntax that allows you to omit the function
keyword, the parentheses around a single parameter, and the curly braces around a single expression:
var double = x => x * 2;
In addition to their shorter syntax, arrow functions also have a lexical this
binding, which means that they inherit the this
value from the enclosing scope. This can help prevent errors caused by the this
keyword being bound to the wrong object in traditional function expressions.
Here's an example of using an arrow function with a lexical this
binding:
var obj = { x: 10, double: function() { var that = this; setTimeout(() => { console.log(that.x * 2); }, 1000); } };
In this example, the arrow function passed to setTimeout
has a lexical this
binding that refers to the obj
object, allowing it to access the x
property and avoid the need to use a that
variable to save the reference to this
.