Arrow Functions in JavaScript: A Simpler Way to Write Functions
Source: Dev.to
Traditional Function Syntax
function greet(name) {
return "hello" + name;
}
Arrow Function Syntax
const greet = (name) => {
return "hello" + name;
};
const greet = name => "hello" + name;
Syntax Breakdown
const functionName = (parameters) => {
// code
};
const→ usually used to define arrow functions(parameters)→ inputs=>→ arrow symbol{}→ function body
Arrow Function with One Parameter
const greet = name => "hello" + name;
If the function has only one statement that returns a value, you can omit the braces and the return keyword.
Arrow Function with Multiple Parameters
const add = (a, b) => a + b;
Arrow Function with Multiple Statements
When the function body contains multiple statements, braces and an explicit return are required:
const sumAndLog = (a, b) => {
const result = a + b;
console.log(result);
return result;
};
Arrow Functions and the this Keyword
Regular Function
const User = {
name: "Tony",
greet: function () {
return this.name;
}
};
User.greet(); // returns "Tony"
Arrow Function
const User = {
name: "Tony",
greet: () => {
return this.name;
}
};
User.greet(); // returns undefined
Arrow functions do not have their own this; they inherit it from the surrounding lexical scope.
Important Points
- Arrow functions must be defined before they are used (no hoisting like function declarations).
- They do not have their own
this,arguments,super, ornew.target. - They are best suited for non‑method functions and callbacks where lexical
thisis desired.