Skip to main content

Command Palette

Search for a command to run...

Arrow Functions in JavaScript: A Simpler Way to Write Functions

Updated
β€’3 min read
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.