JavaScript Lesson 14: Arrow Functions

⚡ JavaScript CourseLesson 14 of 20 · 70% complete

Arrow functions are the modern way to write functions in JavaScript. They are shorter, cleaner, and handle this differently from regular functions.

Syntax Comparison

// Regular function
function add(a, b) {
  return a + b;
}

// Arrow function
const add = (a, b) => {
  return a + b;
};

// Arrow function — implicit return (no braces, no return)
const add = (a, b) => a + b;

// Single parameter — no parentheses needed
const double = n => n * 2;

// No parameters
const greet = () => "Hello World";

Arrow Functions with Arrays

const numbers = [1, 2, 3, 4, 5];

// These all use arrow functions
const doubled = numbers.map(n => n * 2);
const evens = numbers.filter(n => n % 2 === 0);
const sum = numbers.reduce((acc, n) => acc + n, 0);

// Without arrow functions (verbose)
const doubled2 = numbers.map(function(n) {
  return n * 2;
});

The this Difference

// Regular functions have their own "this"
const obj = {
  name: "Alice",
  greet: function() {
    setTimeout(function() {
      // "this" is window here, not obj!
      console.log(this.name); // undefined
    }, 100);
  }
};

// Arrow functions inherit "this" from parent scope
const obj2 = {
  name: "Alice",
  greet: function() {
    setTimeout(() => {
      // "this" is obj2 here!
      console.log(this.name); // "Alice"
    }, 100);
  }
};

🏋️ Practice Task

Rewrite these using arrow functions: (1) function square(n) that returns n squared, (2) function isEven(n) that returns true/false, (3) function getFullName(first, last) that returns a full name string. Then use them in map/filter.

💡 Hint: const square = n => n**2. const isEven = n => n % 2 === 0. const getFullName = (f,l) => f + ” ” + l

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *