Skip to content

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.

13 min read0/6 questions

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:

TypeExamplesNotes
number42, 3.14, -0, NaN, InfinityOne type for integers and decimals
string"hi", 'hi', `hi`Immutable text
booleantrue, false
undefinedundefined"No value was ever assigned"
nullnull"Intentionally empty"
bigint9007199254740993nWhole numbers of any size
symbolSymbol("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:

JavaScript
const word = "hello";const loud = word.toUpperCase();console.log(word); // the original is untouchedconsole.log(loud); try { word[0] = "J"; // you cannot edit a character in place} catch (e) { console.log(e.name, "-", e.message);}
Output
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.

Quick check
Which of these values is not a primitive?
Need a nudge? A hint rules out a wrong answer.

let, const and var

You declare variables with const or let:

  • const means the name cannot be reassigned. Use it by default.
  • let means 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.

Names vs the values they point to
const scores = [90, 85];
NamesObjects in memoryscoresarray[90, 85]

scores is a name bound to an array object. const locks the binding (the arrow), not the array.

1/4
JavaScript
const scores = [90, 85];scores.push(77); // fine: same array, new contentsconsole.log(scores.length); let total = 0;for (const s of scores) total += s;console.log(total); try { scores = []; // reassigning a const name} catch (e) { console.log(e.name);}
Output
Press Run (⌘ Enter) to see what happens.

Why var is avoided

Before 2015 there was only var. It has two behaviours that cause bugs:

  1. Function scope. A var declared inside an if or for block is visible in the whole function. let and const are block scoped: they exist only inside the { } where they are declared.
  2. Hoisting to undefined. The engine moves every var declaration to the top of its function before running it, initialised to undefined. Reading it "too early" gives undefined instead of an error. let and const are hoisted too, but reading them before their line throws a ReferenceError. The gap between the start of the block and the declaration is called the temporal dead zone.
Predict the outputJavaScript

What does this print?

console.log(city);
var city = "Lisbon";
if (true) {
var city = "Oslo";
}
console.log(city);
Need a nudge? Hints walk you through it.

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.

Quick check
What happens?
const team = ["Ada"];
team.push("Sam");
console.log(team.length);
Need a nudge? A hint rules out a wrong answer.

Template literals

Strings in backticks are template literals. They let you embed any expression with ${...} and can span several lines. They replace most + concatenation.

JavaScript
const user = "Priya";const items = 3;const price = 4.5; console.log(`${user} bought ${items} items for $${(items * price).toFixed(2)}`);console.log(`Line oneLine two`);
Output
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:

JavaScript
console.log(typeof 42, typeof "hi", typeof true, typeof undefined);console.log(typeof 10n, typeof Symbol("x"));console.log(typeof {}, typeof []);console.log(typeof function () {});console.log(typeof null);
Output
Press Run (⌘ Enter) to see what happens.
  • typeof null is "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 with value === null.
  • typeof [] is "object" too, because arrays are objects. Use Array.isArray(value) to detect arrays.
  • Functions get their own answer, "function", even though they are objects.
Match the pairs0/5 matched

Match each expression to what it returns.

Choose an item, then its match on the other side.

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:

JavaScript
console.log(0.1 + 0.2);console.log(0.1 + 0.2 === 0.3);console.log(Math.abs(0.1 + 0.2 - 0.3) < Number.EPSILON); // Money: store whole cents as integersconst priceCents = 1999;console.log(`$${(priceCents / 100).toFixed(2)}`);
Output
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.

Predict the outputJavaScript

What does this print?

const qty = Number("three");
console.log(qty * 2);
console.log(qty === qty);
console.log(Number.isNaN(qty));
Need a nudge? Hints walk you through it.
Quick check
A cart adds prices like 19.99 + 5.01 and sometimes shows 25.000000000000004. What is the best fix?
Need a nudge? A hint rules out a wrong answer.
ChallengeEasy

A typeof that tells the truth

typeof says "object" for both null and arrays. Write typeOf(value) that returns a more useful name:

  • "null" for null
  • "array" for arrays
  • otherwise whatever typeof returns ("number", "string", "boolean", "object", ...)
typeOf(null)      → "null"
typeOf([1, 2])    → "array"
typeOf({ a: 1 })  → "object"
typeOf(3)         → "number"
JavaScript
function typeOf(value) { // Handle the two special cases first, then fall back to typeof. return "";}
ChallengeEasy

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.

JavaScript
function formatPrice(cents) { // Split into whole dollars and leftover cents with integer math. return "";}
Key terms
primitive
An immutable single value: number, string, boolean, null, undefined, bigint or symbol.
block scope
A let or const variable exists only inside the { } block where it is declared.
hoisting
Declarations are processed before code runs. var starts as undefined; let/const throw if read before their line.
temporal dead zone
The region before a let/const declaration 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.