Arrow Function Explained, Hoisting, Arguments, Object Return
Arrow functions are a shorter and cleaner way to write functions compared to normal functions.
What is an Arrow Function?
Arrow function uses => syntax and is usually assigned to a variable.
Example:
const add = (a, b) => {
return a + b;
}
Calling the Function:
console.log(add(2, 2)); // Output: 4
Short Syntax (Implicit Return)
If the function has only one line, you can remove return and curly braces.
const add = (a, b) => a + b;
console.log(add(20, 20)); // Output: 40
Arrow Function with Parameters
const add = (a, b) => a + b;
console.log(add(100, 200)); // Output: 300
Using Conditions in Arrow Function
If you want to use conditions, you must use curly braces and return.
const add = (a, b) => {
if (typeof a == "number" && typeof b == "number") {
return a + b;
} else {
return "not a valid input";
}
}
Single Parameter (No Parentheses Needed)
const square = num => num * num;
console.log(square(20)); // Output: 400
Returning Object from Arrow Function
You must wrap the object in parentheses.
const user = () => ({ name: "anil sidhu" });
console.log(user());
Hoisting in Arrow Functions
Arrow functions do not support hoisting like function declarations.
user(); // Error
const user = () => ({ name: "anil sidhu" });
Arguments Keyword
- Works in normal functions
- Does NOT work in arrow functions
const getAll = () => {
console.log(arguments); // Error
}
getAll("green", "apple", "sunday");
Normal function:
function getAll() {
console.log(arguments);
}
Difference: Normal Function vs Arrow Function
- Syntax: Arrow function is shorter
- Hoisting: Works in normal function, not in arrow function
- arguments: Available in normal function, not in arrow function
- this and new keyword: Work in normal function, not in arrow function
Where to Use Arrow Functions
- Callback functions
- Short functions
- Modern JavaScript (like React functional components)