Module 1: JS Foundations

Before async and ES6+ syntax make sense, you need rock-solid mental models of variables, scope, functions, closures, and this. This module builds that ground floor.

1.1 Variables: let, const (and why not var)

Modern JavaScript uses two declarations. Default to const; use let only when the binding must be reassigned. Avoid var entirely β€” it is function-scoped and gets hoisted in confusing ways.

const apiUrl = "https://api.example.com";  // cannot be reassigned
let retries = 0;                            // can be reassigned
retries++;

// const prevents REASSIGNMENT, not mutation:
const user = { name: "Asha" };
user.name = "Veera";      // βœ… allowed β€” the object is mutated
// user = {};             // ❌ TypeError β€” the binding can't change

// Block scoping: let/const live only inside the nearest { }
if (true) {
  let secret = 42;
}
// console.log(secret);   // ❌ ReferenceError
⚠️ The classic var bug

for (var i = 0; i < 3; i++) setTimeout(() => console.log(i)) prints 3, 3, 3 because all callbacks share one function-scoped i. With let, each iteration gets a fresh binding and it prints 0, 1, 2. This is a top-5 interview question.

1.2 Types and Equality

JavaScript has 7 primitive types (string, number, bigint, boolean, undefined, symbol, null) plus objects (which include arrays and functions).

typeof "hi"        // "string"
typeof 42          // "number"
typeof undefined   // "undefined"
typeof null        // "object"  ← famous historical bug, memorize it
typeof []          // "object"  ← use Array.isArray([]) instead
typeof (() => {})  // "function"

// ALWAYS use === (strict equality). == does type coercion:
0 == ""            // true  😱
0 === ""           // false βœ…
null == undefined  // true  (the ONE useful == case)
null === undefined // false

1.3 Functions β€” All the Forms

// 1. Function declaration β€” hoisted (usable before its definition)
function add(a, b) { return a + b; }

// 2. Function expression β€” not hoisted
const subtract = function (a, b) { return a - b; };

// 3. Arrow function (ES6 β€” covered deeply in Module 2)
const multiply = (a, b) => a * b;

// Default parameters
function connect(host = "localhost", port = 8080) {
  return `${host}:${port}`;
}

// Functions are VALUES β€” pass them around (this powers all async code)
function applyTwice(fn, value) {
  return fn(fn(value));
}
applyTwice(x => x * 3, 5);   // 45

1.4 Scope and Closures

A closure is a function that remembers the variables from the scope where it was created, even after that scope has finished executing. This is the single most important concept for understanding callbacks, event handlers, and module patterns.

function makeCounter() {
  let count = 0;                 // private β€” nothing outside can touch it
  return function () {
    count++;                     // the inner function "closes over" count
    return count;
  };
}

const counter = makeCounter();
counter();   // 1
counter();   // 2

const another = makeCounter();
another();   // 1  ← each call to makeCounter creates a fresh closure
πŸ’‘ Why backend devs care

Closures power middleware factories in Express (rateLimit({ max: 100 }) returns a function that remembers the config), memoization caches, and every callback that references outer variables.

1.5 Understanding this

this is determined by how a function is called, not where it is written. Four rules, in priority order:

RuleExamplethis is…
1. newnew User()the newly created object
2. Explicitfn.call(obj) / fn.bind(obj)obj
3. Method calluser.getName()the object before the dot (user)
4. Plain callgetName()undefined (strict mode) / global object
const user = {
  name: "Asha",
  greet() { return `Hi, I'm ${this.name}`; }
};

user.greet();               // "Hi, I'm Asha"   (rule 3)

const fn = user.greet;
fn();                       // "Hi, I'm undefined" β€” detached from user! (rule 4)

const bound = user.greet.bind(user);
bound();                    // "Hi, I'm Asha"   (rule 2)

Arrow functions ignore all four rules β€” they inherit this from the enclosing scope. That's their superpower, covered in Module 2.

1.6 Arrays and Objects β€” the Daily Toolkit

const orders = [
  { id: 1, total: 250, status: "paid" },
  { id: 2, total: 120, status: "pending" },
  { id: 3, total: 900, status: "paid" },
];

// map β€” transform each element
const totals = orders.map(o => o.total);              // [250, 120, 900]

// filter β€” keep matching elements
const paid = orders.filter(o => o.status === "paid"); // 2 orders

// find β€” first match (or undefined)
const order2 = orders.find(o => o.id === 2);

// reduce β€” boil down to one value
const revenue = orders.reduce((sum, o) => sum + o.total, 0);  // 1270

// some / every β€” boolean checks
orders.some(o => o.total > 500);    // true
orders.every(o => o.status === "paid");  // false

// Chaining β€” extremely common in real code:
const paidRevenue = orders
  .filter(o => o.status === "paid")
  .reduce((sum, o) => sum + o.total, 0);   // 1150
🚫 Mutation traps

sort(), reverse(), splice(), push() mutate the original array. map, filter, slice, concat return new ones. Mixing these up causes bugs where "someone else's" data changes unexpectedly. Prefer non-mutating methods, or copy first: [...arr].sort().

Common Beginner Mistakes

  • Using == instead of ===. Turn on ESLint's eqeqeq rule and never think about it again.
  • Believing const makes objects immutable. It only freezes the binding. Use Object.freeze() if you truly need immutability.
  • Detaching methods from objects (const fn = obj.method) and losing this.
  • Forgetting return inside map/filter callbacks with braces: arr.map(x => { x * 2 }) returns undefined for every element.
  • Comparing objects with ===. {} === {} is false β€” objects compare by reference, not contents.

Exercises

Easy 1. Predict the output
let x = 10;
function test() {
  console.log(x);
  let x = 20;
}
test();
Solution

ReferenceError: Cannot access 'x' before initialization. The inner let x creates a new binding for the whole function scope, but it's in the "temporal dead zone" until its declaration line. The outer x is shadowed, not used.

Easy 2. Build a once function

Write once(fn) that returns a version of fn which only runs the first time it's called; later calls return the first result. (Closure practice β€” this exists in Lodash as _.once.)

Solution
function once(fn) {
  let called = false;
  let result;
  return function (...args) {
    if (!called) {
      called = true;
      result = fn(...args);
    }
    return result;
  };
}

const init = once(() => console.log("initialized!"));
init(); // "initialized!"
init(); // (nothing)
Medium 3. Group by status

Using reduce, transform the orders array above into { paid: [...], pending: [...] }.

Solution
const grouped = orders.reduce((acc, order) => {
  (acc[order.status] ??= []).push(order);
  return acc;
}, {});
// Or without ??=:
// if (!acc[order.status]) acc[order.status] = [];
Hard 4. Memoize

Write memoize(fn) that caches results by argument. memoize(slowSquare)(4) computes once; the second call with 4 returns instantly from cache.

Solution
function memoize(fn) {
  const cache = new Map();
  return function (...args) {
    const key = JSON.stringify(args);
    if (!cache.has(key)) {
      cache.set(key, fn(...args));
    }
    return cache.get(key);
  };
}

Closures + Map. Production caches also need eviction (LRU) β€” but this is the core idea behind libraries like memoizee.

Project Module project: Expense Tracker (console)

In Node.js, build a small expense tracker as a module of pure functions: addExpense(list, expense) (non-mutating!), totalByCategory(list), topN(list, n), filterByMonth(list, month). Write a few test calls with console.assert. You'll use every array method and closure concept from this module. Full spec on the Projects page.

Interview Questions from This Module

What is a closure? Give a practical use case.

A closure is a function bundled with its lexical environment β€” it keeps access to variables from the scope where it was defined, even after that scope returns. Practical uses: private state (counters, caches), function factories (a configured rate-limiter middleware), and callbacks that need context.

Explain the difference between var, let, and const.

var: function-scoped, hoisted with value undefined, re-declarable. let: block-scoped, in temporal dead zone until declared, reassignable. const: block-scoped like let, but the binding cannot be reassigned (the value can still be mutated if it's an object).

What does `this` refer to in JavaScript?

It depends on the call site: new binds it to the new instance; call/apply/bind set it explicitly; a method call binds it to the receiver object; a plain function call gives undefined in strict mode. Arrow functions don't have their own this β€” they capture it lexically.

Why does [1,2,3] === [1,2,3] return false?

Objects (arrays included) are compared by reference, not by contents. The two literals create two distinct objects in memory. To compare contents, compare serialized forms or iterate element-by-element.