Introduction
JavaScript is full of features that make writing code easier and faster. Arrow functions stand out as one of the most valuable features added in ES6+. Arrow functions give you a shorter way to write functions, making your code look clean and simple. For beginners, understanding arrow functions is a big step toward writing modern JavaScript like a pro.
What Are Arrow Functions?
Before ES6, writing functions could sometimes feel long and repetitive. Arrow functions solve that by giving you a shorter syntax.
Example with a normal function:
function greet(name) {
return Hello, ${name}!
;
}
With an arrow function:
const greet = (name) => Hello, ${name}!
;
Both do the same thing, but the arrow function is shorter and easier to read.
Shorter Syntax and Simplicity
Arrow functions are popular because they save time when coding. If your function only returns one value, you can even remove the curly braces and return keyword.
Example:
const add = (a, b) => a + b;
console.log(add(2, 8)); // 10
Here, the arrow function is not only shorter but also easier to understand.
Arrow Functions vs this
A major difference between arrow functions and regular functions is how they treat the keyword this. With normal functions, this can change based on how the function is used, but in arrow functions, this sticks to the surrounding scope.
Example:
const person = {
name: "Wisdom",
greet: () => {
console.log(Hi, I'm ${this.name}
);
}
};
person.greet(); // Hi, I'm undefined
Top comments (0)