Home Courses Arrow Function Explained, Hoisting, Arguments, Object Return

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

  1. Works in normal functions
  2. 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

  1. Syntax: Arrow function is shorter
  2. Hoisting: Works in normal function, not in arrow function
  3. arguments: Available in normal function, not in arrow function
  4. this and new keyword: Work in normal function, not in arrow function


Where to Use Arrow Functions

  1. Callback functions
  2. Short functions
  3. Modern JavaScript (like React functional components)


Share this lesson: