The arrow operator, also known as the “fat arrow” operator, is a shorthand syntax for defining functions in JavaScript. It was introduced in ECMAScript 6 (ES6) and is a concise alternative to the traditional function syntax.
(parameter1, parameter2, ...) => {
// function body
}
Here’s an example of a simple arrow function that takes two parameters and returns their sum:
const add = (a, b) => {
return a + b;
}
This is equivalent to the following traditional function definition:
function add(a, b) {
return a + b;
}
JavaScript arrow operator example
Simple example code of an arrow function that uses the Array.prototype.map()
method to double each element in an array:
<!DOCTYPE html>
<html>
<body>
<script>
const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = numbers.map(number => number * 2);
console.log(doubledNumbers);
</script>
</body>
</html>
Output:
There are several advantages to using the arrow operator in JavaScript:
- Conciseness: Arrow functions allow you to write shorter, more concise code. They eliminate the need for the
function
keyword, curly braces, andreturn
statement when writing simple functions. - Clarity: You can make your code more readable by providing a clear and concise syntax for defining functions.
- Implicit returns: Arrow functions with a single expression implicitly return the result of that expression. This can make your code even shorter and more concise.
- Lexical
this
: Arrow functions don’t have their own value, but instead inheritthis
from the enclosing scope. This can help avoid confusion and errors when dealing with nested functions or methods. - No binding of
this
: Arrow functions don’t bindthis
, which means they are not affected by thebind()
,call()
, orapply()
methods. This can make them more predictable and easier to reason about.
Conciseness
// Traditional function syntax
function multiply(a, b) {
return a * b;
}
// Arrow function syntax
const multiply = (a, b) => a * b;
Clarity:
// Traditional function syntax
const isEven = function(number) {
return number % 2 === 0;
}
// Arrow function syntax
const isEven = (number) => number % 2 === 0;
Implicit returns:
// Traditional function syntax
function square(n) {
return n * n;
}
// Arrow function syntax
const square = n => n * n;
Lexical this
:
const person = {
name: "John",
age: 30,
sayHello: function() {
console.log(`Hello, my name is ${this.name}`);
},
sayHelloArrow: () => {
console.log(`Hello, my name is ${this.name}`); // this.name will be undefined
}
}
person.sayHello(); // Output: Hello, my name is John
person.sayHelloArrow(); // Output: Hello, my name is undefined
No binding of this
:
const counter = {
count: 0,
increment: function() {
setInterval(() => {
console.log(this.count++);
}, 1000);
}
}
counter.increment();
Comment if you have any doubts or suggestions on this JS operator topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version