JavaScript Arrow Functions Explained for Beginners
Introduction
Sometimes the traditional functions require more syntax than necessary.
Example:
function add(a, b) {
return a + b;
}
To solve this problem modern JavaScript introduced arrow functions to make functions shorter and more readable. They are also lightweight.
Arrow function version:
const add = (a, b) => {
return a + b;
};
Key idea:
Arrow function reduces boilerplate code.
Basic Arrow Function Syntax
const functionName = (parameters) => {
// code
};
Breakdown:
(parameters) => { function body }
│ │
input logic
Simple example:
const greet = () => {
console.log("Hello!");
};
Arrow Function with One Parameter
The parentheses are optional when there is only one parameter.
const square = x => {
return x * x;
};
Equivalent normal function:
function square(x) {
return x * x;
}
Arrow Function with Multiple Parameters
Parentheses are compulsory when the parameters are more than 1.
const add = (a, b) => {
return a + b;
};
Example:
const multiply = (a, b) => {
return a * b;
};
Implicit Return vs Explicit Return
Explicit Return
When using {} You must write return. It is mandatory to use curly braces when the function logic is more than a single line.
const add = (a, b) => {
return a + b;
};
Implicit Return
If the function has a single expression, you can remove {} and return. If that single expression returns something then that function will also return it. If that single expression is console.log(a+b) then since console.log() return undefined it will also return undefined.
const add = (a, b) => a + b;
Another example:
const square = x => x * x;
This is called implicit return.
Basic Difference Between Arrow Function and Normal Function
| Normal Function | Arrow Function |
|---|---|
Uses function keyword |
Uses => |
| More verbose | Shorter syntax |
| Common in older JavaScript | Modern JavaScript style |
Example comparison:
// Normal function
function greet(name) {
return "Hello " + name;
}
// Arrow function
const greet = name => "Hello " + name;
Arrow Functions with Arrays
Arrow functions are commonly used with array methods like map().
Example:
const numbers = [1, 2, 3, 4];
const squares = numbers.map(num => num * num);
console.log(squares);
Output:
[1, 4, 9, 16]
The Arrow functions make such code clean and readable.
Arrow Function Syntax Breakdown
const add = (a, b) => a + b
│ │ │
variable inputs logic
