Lesson 2 of 50JavaScript basics
Values and Variables
Use let and const correctly, know the seven primitive types, and avoid the classic number and typeof traps.
Every bug report that says "it shows NaN" or "the total is 0.30000000000000004" comes back to the basics below. Interviewers love these too: "what does typeof null return?" and "why is var discouraged?" are warm-up questions in almost every JavaScript screen.
Primitives and objects
Every value in JavaScript is either a primitive or an object. A primitive is a single, immutable value. There are exactly seven kinds:
| Type | Examples | Notes |
|---|---|---|
number | 42, 3.14, -0, NaN, Infinity | One type for integers and decimals |
string | "hi", 'hi', `hi` | Immutable text |
boolean | true, false | |
undefined | undefined | "No value was ever assigned" |
null | null | "Intentionally empty" |
bigint | 9007199254740993n | Whole numbers of any size |
symbol | Symbol("id") | A unique, unguessable key |
Everything else is an object: plain objects {}, arrays [], functions, dates, maps. Objects are mutable collections of properties, and variables hold a reference to them (more on that in the equality lesson).
"Immutable" means you cannot change a primitive in place. String methods always return a new string:
Press Run (⌘ Enter) to see what happens.If you know Python, this matches Python's str: immutable, and methods return new strings. The difference is that JavaScript has two "nothing" values, undefined and null, where Python has only None.
let, const and var
You declare variables with const or let:
constmeans the name cannot be reassigned. Use it by default.letmeans the name can be reassigned. Use it for counters and accumulators.
const does not freeze the value. A const array can still be pushed to, because you are changing the object, not pointing the name somewhere else.
scores is a name bound to an array object. const locks the binding (the arrow), not the array.
Press Run (⌘ Enter) to see what happens.Why var is avoided
Before 2015 there was only var. It has two behaviours that cause bugs:
- Function scope. A
vardeclared inside aniforforblock is visible in the whole function.letandconstare block scoped: they exist only inside the{ }where they are declared. - Hoisting to
undefined. The engine moves everyvardeclaration to the top of its function before running it, initialised toundefined. Reading it "too early" givesundefinedinstead of an error.letandconstare hoisted too, but reading them before their line throws aReferenceError. The gap between the start of the block and the declaration is called the temporal dead zone.
What does this print?
console.log(city);
var city = "Lisbon";
if (true) {
var city = "Oslo";
}
console.log(city);With let, the first line would throw ReferenceError: Cannot access 'city' before initialization, and the inner city would be a separate variable. Errors that point to the real mistake are better than silent undefined. Modern style guides and linters (ESLint's no-var rule) ban var entirely.
const team = ["Ada"];
team.push("Sam");
console.log(team.length);Template literals
Strings in backticks are template literals. They let you embed any expression with ${...} and can span several lines. They replace most + concatenation.
Press Run (⌘ Enter) to see what happens.The expression inside ${} can be anything: arithmetic, a function call, a ternary. Python's f-strings (f"{user}") are the closest match.
typeof and its quirks
typeof returns a string naming the type of a value. It is mostly sensible, with two famous exceptions:
Press Run (⌘ Enter) to see what happens.typeof nullis"object". This is a bug from the first implementation in 1995 (null was stored with the same type tag as objects). Fixing it would break old websites, so it stays. Check for null withvalue === null.typeof []is"object"too, because arrays are objects. UseArray.isArray(value)to detect arrays.- Functions get their own answer,
"function", even though they are objects.
Match each expression to what it returns.
Numbers are 64-bit floats
JavaScript has one number type, stored as a 64-bit floating point value (IEEE 754 "double"), the same as Python's float. That has two consequences you will hit in real work.
Decimals are approximate. Binary floating point cannot represent 0.1 exactly, so small errors appear:
Press Run (⌘ Enter) to see what happens.For money, store integer cents (or use a decimal library) and only format at the edge. For comparisons, check that the difference is below a tiny tolerance.
Integers are exact only up to 2⁵³ − 1 (Number.MAX_SAFE_INTEGER, about 9 quadrillion). Database IDs and timestamps in nanoseconds can exceed that. For those, use bigint by adding n: 2n ** 64n. You cannot mix bigint and number in arithmetic without converting.
NaN
NaN ("not a number") is what you get from math that has no numeric answer: Number("abc"), 0 / 0, undefined + 1. It spreads through every calculation it touches, and it is the only value not equal to itself.
What does this print?
const qty = Number("three");
console.log(qty * 2);
console.log(qty === qty);
console.log(Number.isNaN(qty));19.99 + 5.01 and sometimes shows 25.000000000000004. What is the best fix?A typeof that tells the truth
typeof says "object" for both null and arrays. Write typeOf(value) that returns a more useful name:
"null"fornull"array"for arrays- otherwise whatever
typeofreturns ("number","string","boolean","object", ...)
typeOf(null) → "null"
typeOf([1, 2]) → "array"
typeOf({ a: 1 }) → "object"
typeOf(3) → "number"Format cents as dollars
Prices are stored as integer cents to avoid floating point errors. Write formatPrice(cents) that returns a display string with a dollar sign and exactly two decimal places. Negative amounts put the minus sign before the dollar sign.
formatPrice(1999) → "$19.99"
formatPrice(5) → "$0.05"
formatPrice(-250) → "-$2.50"No thousands separators. cents is always an integer.
- primitive
- An immutable single value: number, string, boolean, null, undefined, bigint or symbol.
- block scope
- A
letorconstvariable exists only inside the{ }block where it is declared. - hoisting
- Declarations are processed before code runs.
varstarts asundefined;let/constthrow if read before their line. - temporal dead zone
- The region before a
let/constdeclaration where reading the variable throws a ReferenceError. - NaN
- "Not a number", the result of failed numeric operations. Never equal to itself; test with
Number.isNaN. - template literal
- A backtick string that can embed expressions with
${...}and span lines.