Lesson 24: Mastering JavaScript Arrrow functions with challenges!

manoj ymkmanoj ymk
4 min read

⚡ What Are Arrow Functions?

Arrow functions are a more concise syntax to write functions in JavaScript. They’re ideal for short, simple tasks like one-liners or callbacks.

✅ Basic Syntax:

let func = (arg1, arg2, ..., argN) => expression;

This is equivalent to:

let func = function(arg1, arg2, ..., argN) {
  return expression;
};

🧪 Examples:

let sum = (a, b) => a + b;
console.log(sum(2, 3)); // 5

let double = n => n * 2;
console.log(double(4)); // 8

let sayHi = () => console.log("Hello!");
sayHi(); // Hello!

📝 Multiline Form:

If your function body has multiple statements, use {} and explicitly return.

let sum = (a, b) => {
  let result = a + b;
  return result;
};

🔹 2. Fill Any Gaps

❓When to Use Parentheses

ParametersSyntax
No params() => ...
One paramx => ...
Multiple params(x, y) => ...

⛔ Implicit Return Only for Expression

This works:

let getFive = () => 5;

This won’t return anything:

let getObj = () => { name: "John" }; // undefined!

✅ Fix with parentheses:

let getObj = () => ({ name: "John" });

💥 return is required with {}

let greet = name => {
  let msg = `Hi ${name}`;
  return msg;
};

🔹 3. Challenge Me Deeply

🟢 Basic

  1. Convert this to an arrow function:

     function multiply(x, y) {
       return x * y;
     }
    
  2. Write an arrow function that returns the square of a number.

🟡 Intermediate

  1. Write an arrow function that returns the greater of two numbers.

  2. Use an arrow function inside setTimeout to log "Done!" after 2 seconds.

  3. Write an arrow function that returns an object { name: "Alice" }.

🔴 Advanced

  1. Build a simple factory function using arrow functions.

  2. Write a higher-order function that takes a function and returns a throttled version using arrow functions.

  3. Implement a dynamic greeting using a ternary with arrow functions (as shown in your example).


🔹 4. Interview-Ready Questions

📚 Conceptual

  • How do arrow functions differ from regular function expressions?

  • What are the rules around return in arrow functions?

🧠 Tricky Cases

  • Why does () => { name: "John" } return undefined?

  • How do you return an object literal from an arrow function?

⚙️ Practical

  • How can arrow functions improve readability in array methods like .map() or .filter()?

  • Where would using arrow functions be a bad idea?


🔹 5. Real-World Usage

🔧 Common Scenarios

  • Array methods:

      const nums = [1, 2, 3];
      const squares = nums.map(n => n * n);
    
  • Event listeners (with caveats on this):

      button.addEventListener('click', () => alert('Clicked!'));
    
  • Callbacks:

      jsCopyEditsetTimeout(() => console.log('Done!'), 1000);
    
  • React Components / Hooks:

      const handleClick = () => setCount(count + 1);
    

🔹 6. Remember Like a Pro

🧠 Mnemonics

  • Arrow = Always concise

  • () => value = like "input gives output"

  • Curly brace? Explicit return required!

📌 Quick Cheatsheet

FormExampleReturns
One-liner, one paramx => x + 1x + 1
One-liner, no param() => 4242
Object return() => ({ name: "Alex" }){ name: "Alex" }
Multiline(x, y) => { return x + y; }x + y

🔹 7. Apply It in a Fun Way

🎉 Project: Mini-Quiz Grader

const grade = (score) => {
  return (score >= 90) ? 'A' :
         (score >= 80) ? 'B' :
         (score >= 70) ? 'C' :
         (score >= 60) ? 'D' : 'F';
};

console.log(grade(92)); // A
console.log(grade(71)); // C

🧪 Bonus Twist

Use arrow functions + .map() to grade an entire class:

const scores = [85, 92, 58, 77];
const grades = scores.map(score => grade(score));
console.log(grades); // [ 'B', 'A', 'F', 'C' ]

🧠 Bonus Insights

🧭 Common Mistakes

  • Forgetting to return with {} block

  • Confusing when parentheses are needed

  • Misusing arrow functions with this (covered in future lessons)

🚀 Performance Note

Arrow functions don’t create their own this, which can be a performance optimization in some use cases.

🧰 Used In:

  • React (useEffect(() => {...}))

  • Node.js callbacks

  • Functional programming patterns

  • Array method chains

0
Subscribe to my newsletter

Read articles from manoj ymk directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

manoj ymk
manoj ymk