JavaScript fundamentals
A few small JavaScript rules explain most strange frontend bugs. Variables and scope, closures, the this keyword, values versus references, shallow and deep copies, strict equality, and array methods that change the array. This lesson shows all of them with the online shop example.
Author: bezzad
Contents
The problem: bugs that throw no error
Our online shop team got bug reports for a whole week. None of them throws an error. The result is just wrong:
- Sort by price shows the 100 dollar item before the 25 dollar item.
- After sorting for the “cheapest first” view, the order of the main product list also changed.
- A user in the checkout form changes the city of the address, and the saved order’s address changes too.
- Free shipping (cost 0) shows as 5 dollars on the checkout page.
- All three “Add to cart” buttons add the wrong product.
All of these come from a few basic JavaScript rules. Once you know the rules, you spot these bugs in code review from far away.
Variables: const, let and var
const shopName = 'Levelwise Shop'; // cannot be reassigned
let total = 0; // can be reassigned
total = 120;
if (total > 100) {
let discount = 10; // lives only inside this block
var oldStyle = 'leaks';
}
console.log(oldStyle); // 'leaks'
console.log(discount); // ReferenceError: discount is not defined
- The const keyword only means this name cannot get a new value. If the value is an object, the object’s contents can still change.
- The let and const keywords belong to the block, the part between two curly braces. They are not visible outside it.
- The var keyword belongs to the whole function and leaks out of the block. This causes bugs.
- Simple rule: always const. If you really must change the value, let. Do not use var.
Hoisting and the temporal dead zone
Before the code runs, JavaScript knows all declarations in a scope. But they behave differently:
console.log(a); // undefined: var exists, but has no value yet
var a = 1;
console.log(b); // ReferenceError: Cannot access 'b' before initialization
let b = 2;
greet(); // works: function declarations are hoisted fully
function greet() { console.log('hi'); }
- A var variable exists from the start of the scope, with the value undefined.
- The let and const variables also exist from the start, but you cannot touch them before their line. This gap is called the temporal dead zone (TDZ).
- A function declaration with the function keyword is hoisted fully. So you can call it before its line.
Closures
A function remembers the variables of the place where it was created, even after the outer function has finished. This is called a closure.
A real use: the shop’s search box. We do not want to send a request to the server for every letter the user types. We wait until the user stops typing for 300 ms (debounce):
function debounce(fn, ms) {
let timerId; // remembered by the inner function
return (...args) => {
clearTimeout(timerId);
timerId = setTimeout(() => fn(...args), ms);
};
}
const search = debounce((text) => console.log('search for', text), 300);
search('p');
search('ph');
search('phone'); // prints only "search for phone", after 300 ms
- The debounce function runs once and finishes.
- The returned function can still use the timerId variable. That is the closure.
- Each call cancels the previous timer. Only the last keystroke reaches the server.
- The timerId variable is not visible from outside. So a closure is also a way to keep data private.
The classic bug: var in a loop
A developer creates three click handlers for three products in a loop. With var, all three buttons add the wrong product. See the same behavior with setTimeout:
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0);
}
// 3 3 3
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0);
}
// 0 1 2
- With var there is only one variable i for the whole loop. All three functions point to that one variable.
- When the functions run, the loop has finished and i is 3. So all three see 3. In the shop, all three buttons ask for product number 3, which does not exist.
- With let the loop creates a fresh i for each round. Each function keeps its own i.
The this keyword
For normal functions, this does not depend on where the function is written. It depends on how it is called. An arrow function has no this of its own; it takes this from outside.
const cart = {
items: ['pen', 'book'],
count() {
return this.items.length;
},
countLater() {
setTimeout(() => {
console.log(this.items.length); // arrow: same this as countLater
}, 0);
},
};
cart.count(); // 2: called as cart.count(), so this is cart
const count = cart.count;
count(); // TypeError: this is undefined
const fixed = cart.count.bind(cart);
fixed(); // 2: bind fixes this forever
cart.countLater(); // prints 2
- Calling with a dot (like cart.count) means this is the object before the dot.
- Calling it alone, after taking the function out of the object, means this is undefined (in modules and strict mode). So you get an error.
- When you pass a normal function to addEventListener, the browser calls it with this set to the element the listener is on, not cart.
- The bind method makes a new function whose this is always fixed.
- An arrow function takes this from where it is written. That is great for a callback inside a method. But it is not good for the object method itself, because there this is the this outside the object, not the object.
Values and references
Simple values (primitives) are copied. They are: string, number, bigint, boolean, undefined, null and symbol. Everything else is an object (arrays and functions too). A variable that holds an object only keeps a reference to it.
let price = 100;
let newPrice = price; // copies the value
newPrice = 80;
console.log(price); // 100
const cart = { items: [] };
const sameCart = cart; // copies the reference, not the object
sameCart.items.push('pen');
console.log(cart.items); // ['pen']
console.log({ id: 1 } === { id: 1 }); // false: two different objects
Shallow copy and deep copy
This is the checkout form bug:
const order = { id: 7, address: { city: 'Tehran' } };
const copy = { ...order }; // shallow copy
copy.address.city = 'Shiraz';
console.log(order.address.city); // 'Shiraz': the inner object is shared
const deep = structuredClone(order); // deep copy
deep.address.city = 'Yazd';
console.log(order.address.city); // still 'Shiraz'
- The spread operator (three dots) copies only the first level. Inner objects are still shared.
- The structuredClone function copies all levels. It also copies dates, Maps and Sets correctly. It exists in today’s browsers and in Node.js.
- The structuredClone function cannot copy functions; it throws a DataCloneError. An instance of a class also becomes a plain object.
- The old JSON trick (stringify, then parse) turns dates into strings and drops undefined and functions.
In React and Vue you usually do not need a deep copy. Copy only the level you change:
const updated = { ...order, address: { ...order.address, city: 'Yazd' } };
Equality: double and triple equals
The triple equals operator (===) does not change types. The double equals operator (==) converts types first, with rules that surprise you:
0 == ''; // true
'0' == 0; // true
'0' == false; // true
null == undefined; // true
null === undefined; // false
NaN === NaN; // false: use Number.isNaN(value)
Always use triple equals. Some teams allow one exception: comparing with null using double equals, which checks null and undefined together.
Falsy values and ?? versus ||
These eight values act like false in a condition: false, 0, -0, 0n, the empty string, null, undefined and NaN. Everything else is truthy, even the string ‘0’, an empty array and an empty object.
The free shipping bug comes from here:
const order = { shippingCost: 0 }; // free shipping
const wrong = order.shippingCost || 5; // 5: 0 is falsy
const right = order.shippingCost ?? 5; // 0: ?? replaces only null and undefined
- The || operator returns the default for any falsy value. So 0 and the empty string are replaced too.
- The ?? operator returns the default only for null and undefined. For numbers and text, this is usually what you want.
Optional chaining
const city = user?.address?.city; // undefined if user or address is missing
const label = product.badge?.toUpperCase() ?? 'No badge';
onDone?.(); // call only if onDone exists
If anything before ?. is null or undefined, the whole expression becomes undefined without an error. Do not use it everywhere. If the data must exist, it is better to see the error early than to hide the bug.
Arrays: change the array or return a new one
Some methods change the same array. Some return a new array.
| Changes the same array | Returns a new array |
|---|---|
| The push, pop, shift, unshift methods | The concat method, or spread |
| The splice method | The slice method, the toSpliced method |
| The sort method | The toSorted method |
| The reverse method | The toReversed method |
| Direct change by index | The with method |
| The map and filter methods |
const prices = [25, 100, 9];
const sorted = prices.toSorted((a, b) => a - b); // [9, 25, 100], a new array
console.log(prices); // [25, 100, 9], unchanged
prices.sort(); // [100, 25, 9]: compared as text!
prices.sort((a, b) => a - b); // [9, 25, 100], changes prices itself
- The sort method without a compare function turns everything into text and compares the texts letter by letter. The text “100” comes before “25”, because “1” comes before “2”. This is the shop’s first bug.
- For numbers, always pass a compare function. For names, use the localeCompare method.
- The sort method changes the same array and returns that same array. So saving the result in a new variable does not make a copy. This is the shop’s second bug.
- In React and Vue, changing state directly can stop the page from updating. The toSorted, toReversed, toSpliced and with methods (from ES2023) are the non-changing versions of those methods.
Modules (ES modules)
Each file is a module. Anything not exported is not visible outside the file.
// cart.js
export const MAX_ITEMS = 50;
export function addItem(cart, item) {
return { ...cart, items: [...cart.items, item] };
}
export default function createCart() {
return { items: [] };
}
// app.js
import createCart, { addItem, MAX_ITEMS } from './cart.js';
const cart = addItem(createCart(), 'pen');
- Each file has its own scope. Variables do not leak out as globals.
- Module code always runs in strict mode.
- In the browser you use the script tag with the type attribute set to module. Like defer, this script waits until the HTML is read.
- A normal import statement sits at the top of the file, and build tools can analyze it ahead of time. The import function (dynamic import) returns a promise and downloads code only when it is needed. For example, the checkout page code only when the user goes to checkout.
- A file can have at most one default export. Many teams prefer named exports, because searching and renaming are easier.
Common mistakes
| Mistake | Result | Better way |
|---|---|---|
| Using var | The variable leaks out of the block. The loop bug. | const by default, let when needed. |
| The sort method with no compare function for numbers | 100 comes before 25. | Pass a compare function that returns a minus b. |
| The sort method on state or shared data | The original data changes too. | The toSorted method, or copy first. |
| Spread copy for a nested object | The inner object stays shared. | Copy the changed level too, or structuredClone. |
| The double equals operator | Surprising type conversion. | The triple equals operator. |
| The OR operator for a number default | Zero is replaced. | The ?? operator. |
| Taking a method out of its object | this is undefined, and an error. | The bind method, or an arrow function around it. |
| An arrow function as an object method | this does not point to the object. | A normal method. |
Summary in seven lines
- const is the default, let only when the value changes. Do not use var.
- A closure keeps the variables of the place where it was made. It is useful for debounce and private data. With var in a loop, all functions see one variable.
- In a normal function, this depends on how it is called. An arrow function takes it from outside.
- A simple value is copied. For an object, only the reference is copied.
- The spread operator makes a shallow copy. The structuredClone function makes a deep copy.
- Always triple equals. For defaults use ??, not ||.
- The sort, splice and push methods change the array. The map, filter and toSorted methods make a new array. The sort method without a compare function compares texts.