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.
Introduced in ES6, they improve:
Readability
Conciseness
Modern JavaScript style
Traditional Function vs Arrow Function
Normal Function
function greet(name) {
return `Hello ${name}`;
}
Arrow Function
const greet = (name) => {
return `Hello ${name}`;
};
Function Transformation
flowchart LR
A[function greet(name)] --> B[(name) =>]
Basic Arrow Function Syntax
const functionName = (parameters) => {
// code
};
Example
const add = (a, b) => {
return a + b;
};
console.log(add(10, 5));
Output
15
Arrow Function With One Parameter
If there is only one parameter, parentheses are optional.
Example
const square = number => {
return number * number;
};
console.log(square(5));
Output
25
Arrow Function With Multiple Parameters
Use parentheses when multiple parameters exist.
Example
const multiply = (a, b) => {
return a * b;
};
console.log(multiply(4, 3));
Output
12
Explicit Return
When using {}, you must write return.
Example
const subtract = (a, b) => {
return a - b;
};
Implicit Return
If the function has a single expression, return is automatic.
Example
const subtract = (a, b) => a - b; console.log(subtract(10, 3));
Output
7
Explicit vs Implicit Return
Implicit Return Visualization
flowchart LR
A[(a,b)=>a+b] --> B[Return automatically]
Simple Greeting Example
const greet = name => `Hello ${name}`;
console.log(greet("Ali"));
Output
Hello Ali
Arrow Functions Inside map()
Arrow functions are commonly used with array methods.
Example
const numbers = [1, 2, 3, 4]; const doubled = numbers.map(number => number * 2); console.log(doubled);
Output
[2, 4, 6, 8]
Why Arrow Functions Are Popular
Basic Difference Between Arrow and Normal Functions
Avoid This Beginner Mistake
Incorrect:
const add = a, b => a + b;
Correct:
const add = (a, b) => a + b;
Assignment
1. Normal Function
function square(number) {
return number * number;
}
console.log(square(5));
2. Rewrite Using Arrow Function
const square = number => number * number; console.log(square(5));
3. Even or Odd Checker
const checkEvenOdd = number => number % 2 === 0 ? "Even" : "Odd"; console.log(checkEvenOdd(10)); console.log(checkEvenOdd(7));
4. Use Arrow Function Inside map()
const numbers = [1, 2, 3, 4]; const squares = numbers.map(number => number * number); console.log(squares);
Key Takeaways
Arrow functions are heavily used in modern JavaScript applications:
React
Node.js
Next.js
Express APIs
Array methods
They make code shorter, cleaner, and easier to read.
No attachments.
0 Comments
Sign in to join the conversation
No comments yet. Be the first to comment!