JavaScript Basics
JavaScript is the only language that runs natively in every browser, and its reputation for oddness comes from a handful of design decisions you can learn in an afternoon. Values, variables, operators, control flow, functions, arrays, and objects — that is essentially the whole core. The surprises live in the details: type coercion in comparisons, objects handed around by reference, and functions that remember where they were created.
This lesson builds the mental models that prevent the classic beginner bugs. You will learn how to declare values safely, why equality has two forms, how functions really work, and how arrays and objects differ from the primitive values they hold.
Values, Variables, and Types
JavaScript has seven primitive types — strings, numbers, booleans, null, undefined, bigint, and symbol — plus objects, which cover everything else, including arrays and functions. Primitives are immutable: the string "bread" can never be changed in place, only replaced by a new string.
Three declaration keywords exist. const is the default: the binding cannot be reassigned. let is for counters and accumulators whose value legitimately changes. var is the legacy form with function scoping and hoisting quirks — avoid it in modern code.
const TAX_RATE = 0.08;
let subtotal = 24.5;
function addLine(itemPrice) {
subtotal = subtotal + itemPrice;
return subtotal;
}
addLine(3.25);
addLine(11);
const total = subtotal * (1 + TAX_RATE);
console.log(total.toFixed(2)); // "39.68"
Note what happened: subtotal changed even though the goal was mostly fixed configuration; only the binding was reassigned, which let allows. Constants protect you from accidental reassignment, and they signal intent to the next reader.
Equality, Truthiness, and Coercion
JavaScript has two equality operators, and the difference explains a whole category of interview questions. Strict equality (===) compares value and type with no conversion. Loose equality (==) converts operands before comparing, producing results like the famous comparison of an empty string to zero being false because the string is first converted to a number NaN, and NaN never equals anything.
| Expression | Result | Why |
|---|---|---|
0 === "0" | false | Different types, no conversion |
0 == "0" | true | String coerced to number |
null == undefined | true | Loose equality pairs these two only |
NaN === NaN | false | NaN is never equal to itself |
[] == false | true | Both become 0 after coercion |
Boolean("0") | true | Any non-empty string is truthy |
The practical rule: always use === and !==, and do explicit conversions with Number(), String(), or Boolean() when you mean them. Truthiness still matters in conditionals — empty strings, zero, null, undefined, and NaN are falsy; everything else is truthy, including "0" and "false".
Control Flow: Conditionals and Loops
if/else if/else is straightforward. Prefer early returns over deep nesting so the happy path stays left-aligned. For multi-way dispatch on a fixed set of values, a switch statement (with break at every case, or fall-through only when deliberate) reads better than a ladder of comparisons.
Traditional for loops still appear, but iteration protocols have taken over. for...of walks the values of any iterable — arrays, strings, Maps, Sets — and for...in walks keys, which is usually what you want only for plain objects.
const cart = [
{ name: "Sourdough", price: 6 },
{ name: "Rye", price: 5.5 },
{ name: "Baguette", price: 3 },
];
let totalCents = 0;
for (const line of cart) {
totalCents += Math.round(line.price * 100);
}
const labels = cart.map((line) => line.name + " — " + line.price.toFixed(2));
console.log(labels.join("; "));
console.log("Total cents:", totalCents);
break exits the innermost loop; continue skips to the next iteration. Array methods like map, filter, reduce, find, and some express the same ideas declaratively and chain well.
Functions: Declarations, Expressions, and Arrows
Functions are values. A function declaration is hoisted whole, so it can be called before its line of definition. A function expression is not. Arrow functions provide a shorter syntax and, crucially, do not bind their own this — they inherit it from the surrounding scope, which makes them ideal as callbacks but wrong as methods you intend to detach.
Parameters can have defaults, and the rest operator collects trailing arguments into a real array:
function priceWithDiscount(price, discount = 0.1, ...couponNotes) {
const net = price * (1 - discount);
return {
net: Number(net.toFixed(2)),
notes: couponNotes.length ? couponNotes : ["no notes"],
};
}
console.log(priceWithDiscount(20)); // 18, default discount
console.log(priceWithDiscount(20, 0.25, "VIP")); // 15 with a note
Functions that take an options object scale better than long parameter lists: renderCard({ title, size = "md", highlighted = false }) stays readable at five options, positional parameters do not.
Arrays and Objects: Reference Semantics
Primitives compare by value; objects compare by reference. Assigning an object copies the pointer, not the data. Mutating the copy mutates the original — the bug that launches a thousand Stack Overflow threads.
const original = { items: ["flour", "water"], count: 2 };
const alias = original;
alias.count = 99;
console.log(original.count); // 99 — same object!
const shallow = { ...original }; // new object, same inner array
const deepItems = [...original.items]; // new array
shallow.items.push("salt");
console.log(original.items.length); // 3 — shallow copies share arrays
Spread syntax (...) creates shallow copies at one level. Arrays being objects, they carry a large standard library: push, pop, slice, splice, concat, find, filter, map, reduce, sort (which sorts in place — copy first with toSorted or [...arr].sort() when you need the original preserved).
Destructuring and Spread in Everyday Code
Destructuring pulls values out of structures by name, which documents what a function needs:
const order = {
id: "A-104",
customer: { name: "Mira", tier: "gold" },
lines: 3,
};
const { id, customer: { name }, lines = 1 } = order;
const [firstLine] = order.lines ? ["…"] : [];
console.log(id, name, lines, firstLine);
Object spread merges configurations: const config = { ...defaults, ...overrides }. Because it is shallow, nested objects from overrides replace defaults wholesale rather than merging — remember that when combining options trees.
Error Handling: try, catch, throw
JavaScript has no checked exceptions and no return-code convention; it has try, catch, finally, and throw, plus the reality that promise rejections travel the same road one microtask later. The basic shape: code that might fail goes inside try, recovery logic lives in catch, and finally runs whether the attempt succeeded or not — perfect for closing resources.
function parseConfig(raw) {
let config;
try {
config = JSON.parse(raw);
} catch (error) {
throw new Error("Config is not valid JSON: " + error.message);
}
if (typeof config.port !== "number") {
throw new RangeError("port must be a number, received " + typeof config.port);
}
return config;
}
try {
const cfg = parseConfig('{"port": "8080"}');
console.log("Listening on", cfg.port);
} catch (error) {
if (error instanceof RangeError) {
console.warn("Using default port:", error.message);
} else {
throw error;
}
}
Three habits separate production error handling from demo code. Catch specific failure modes and rethrow what you do not understand — a blanket catch that swallows everything turns a loud bug into a silently wrong answer. Attach context when rethrowing, by wrapping the message or using the cause option, so the eventual log tells you which call failed. And never let an error object cross an API boundary unconverted: serialize a stable shape with a code and a message at the edge, keep rich error instances inside.
For asynchronous code, try and catch inside an async function cover awaited rejections. Without async, attach a catch handler or the rejection reaches the window's unhandled-rejection hook and the user sees nothing at all.
📝Equality, at a glance
Use the strict form for comparisons unless you have a documented reason not to. The loose form's conversion rules — including the surprising pairing of null with undefined, and the way an empty string and a boolean false both collapse toward zero — exist for backward compatibility with the language's earliest days, not because they produce intuitive results. Explicit conversions at the boundaries of your system, and strict equality everywhere inside it, is the pattern that survives code review.
Common Mistakes
Comparing values with ==
Fix: Use === everywhere; convert explicitly with Number() or String() when coercion is intended.
Mutating an object received as a parameter
Fix: Copy first with spread, then mutate the copy — callers keep their original.
Using var in block scopes
Fix: Use const by default and let for reassigned bindings; var leaks to the enclosing function.
Assuming .sort() returns a new array
Fix: It sorts in place — spread into a new array first if you need the original order.
Interview Questions
Q1: What is the difference between let and const, and when would you use var?
let and const are block-scoped; const bindings cannot be reassigned (though object contents stay mutable). var is function-scoped, hoisted and initialized as undefined, and leaks into enclosing scopes — avoid it.
Q2: Why does NaN === NaN evaluate to false?
NaN is the result of undefined numeric operations and is defined as unequal to everything, including itself. Use Number.isNaN(x) to test for it.
Q3: Explain pass-by-value versus pass-by-reference in JavaScript.
Primitives are copied by value into parameters. Objects are copied by reference — the parameter points at the same object, so mutations are visible to the caller.
Q4: What does the spread operator do for objects versus arrays?
For arrays it creates a shallow copy or concatenates; for objects it creates a new object with copied own enumerable properties. Both are shallow — nested structures are still shared.
Key Takeaways
- Prefer const, then let; never reach for var in modern code.
- Use === for comparisons and treat truthiness as a deliberate conversion, not a surprise.
- Functions are values — declarations hoist, expressions do not, arrows inherit this.
- Objects and arrays are assigned by reference; spread creates only a shallow copy.
- Array methods like map, filter and reduce express transformations more clearly than index loops.
- Destructuring and options objects keep function signatures readable as parameters grow.