JavaScript Advanced Day 1: Advanced Functions & Patterns

Goal of this Day

Today you will learn:

By the end, you will write cleaner, reusable, and more powerful functions.

Step 1: Higher-Order Functions

A function that takes another function as argument or returns a function.


const add = x => y => x + y;
console.log(add(2)(3)); // 5

Step 2: IIFE

Immediately Invoked Function Expression runs immediately:


(function(){
  console.log("IIFE runs immediately!");
})();

Step 3: Currying & Partial Application

Transform a function with multiple arguments into a sequence of functions:


const multiply = x => y => x * y;
console.log(multiply(2)(3)); // 6

Step 4: Function Composition

Combine multiple functions to produce a new function:


const compose = (f, g) => x => f(g(x));

const double = x => x * 2;
const square = x => x * x;

console.log(compose(square, double)(3)); // 36

Practice


const add = x => y => x + y;
console.log(add(2)(3));

(function(){
  console.log("IIFE runs immediately!");
})();

Task

Complete the following:

Example:


// Curried multiplication function
const multiply = x => y => x * y;
console.log(multiply(4)(5)); // 20

// IIFE printing name
(function(){
  console.log("Alex");
})();