iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

JS Arrow Functions

Arrow functions are a shorter syntax for writing functions. Beyond being terse, they have one important behavioural difference: they don't have their own this.

The three forms

JS
// Single expression — implicit return
const double = (x) => x * 2;

// Single param — parentheses optional
const square = x => x * x;

// Multiple statements — needs braces and explicit return
const greet = (name) => {
  const msg = `Hi, ${name}!`;
  return msg;
};

// Returning an object literal — wrap in parens
const point = (x, y) => ({ x, y });

Arrow vs. regular function

FeatureArrowRegular
Own thisNo — inherits enclosing scopeYes — set by call site
Own argumentsNoYes
Hoisted?NoDeclarations: yes
Usable with newNoYes
Best forCallbacks, methods on classes (often)Top-level functions, methods that need this

The this behaviour matters

JS
class Counter {
  constructor() { this.count = 0; }

  // ✅ Arrow uses the Counter instance as `this`
  increment = () => { this.count++; };

  // ❌ A regular method passed as a callback loses its `this`
  incrementBad() { this.count++; }
}

const c = new Counter();
setTimeout(c.increment, 100);     // works ✓
setTimeout(c.incrementBad, 100);  // breaks ✗ — this is undefined
Tip: Reach for arrow functions for everything except object methods that should be re-bindable, constructors, and generator functions. They're the modern default for callbacks.

Example

Example
<!DOCTYPE html>
<html>
<body>

<p id="out"></p>

<script>
document.getElementById("out").textContent = "Hello from JS Arrow Functions!";
</script>

</body>
</html>
Try it Yourself »

Exercise

Return an object literal from an arrow without using a function body.

const point = (x, y) => { x, y })

Test yourself

Q1. Arrow functions are NOT good for…
Q2. Return an object literal from an arrow with…
Q3. Arrow functions cannot be used with…

Discussion

Loading…