Arrow Functions in JavaScript: A Simpler Way to Write Functions

π What Are Arrow Functions?
Arrow functions are a shorter way to write functions in JavaScript.
They reduce extra code (boilerplate) and look cleaner.
π 1οΈβ£ Normal Function vs Arrow Function
β Normal Function
function greet(name) {
return "Hello " + name;
}
β Arrow Function
const greet = (name) => {
return "Hello " + name;
};
See how it removes function keyword?
Thatβs the main idea.
π Basic Arrow Function Syntax
const functionName = (parameters) => {
// code
};
Breakdown:
(parameters) => { }
β β
inputs function body
π Arrow Function with One Parameter
If there is only one parameter, brackets are optional.
const greet = name => {
return "Hello " + name;
};
Both are correct:
(name) => {}
name => {}
π Arrow Function with Multiple Parameters
If there are multiple parameters, use brackets.
const add = (a, b) => {
return a + b;
};
console.log(add(5, 3)); // 8
π Implicit Return vs Explicit Return
This is very important π₯
πΉ Explicit Return (with return keyword)
const square = (num) => {
return num * num;
};
We used { } and return.
πΉ Implicit Return (No return keyword)
If function has only one line, we can remove {} and return.
const square = num => num * num;
console.log(square(4)); // 16
π This automatically returns the value.
That is called implicit return.
π Another Example
Normal function:
function multiply(a, b) {
return a * b;
}
Arrow version:
const multiply = (a, b) => a * b;
Cleaner and modern β
π Basic Difference: Normal vs Arrow Function
| Normal Function | Arrow Function |
|---|---|
Uses function keyword |
Uses => |
| More code | Shorter |
Has its own this |
Does not have its own this |
| Traditional style | Modern style |
β For now, just remember:
Arrow functions are mostly used for short and simple tasks.
π Diagram Idea β Transformation
Normal Function
function add(a, b) {
return a + b;
}
β
Arrow Function
const add = (a, b) => a + b;
π Syntax Breakdown
const add = (a, b) => a + b;
β β β
variable inputs return value
π Assignment Practice
1οΈβ£ Write Normal Function to Calculate Square
function square(num) {
return num * num;
}
2οΈβ£ Rewrite Using Arrow Function
const square = num => num * num;
3οΈβ£ Even or Odd Using Arrow Function
const checkEvenOdd = num =>
num % 2 === 0 ? "Even" : "Odd";
console.log(checkEvenOdd(4)); // Even
4οΈβ£ Use Arrow Function Inside map()
let numbers = [1, 2, 3, 4];
let doubled = numbers.map(num => num * 2);
console.log(doubled);
Output:
[2, 4, 6, 8]
π Final Understanding
Arrow functions:
Are shorter
Improve readability
Are widely used in modern JavaScript
Work great with map(), filter(), etc.
