1.2 Variables and Data Types

Aligned outcomes:

SLO 1

Describe the software development life-cycle.

Section 1.2 grounds the life-cycle vocabulary in the programming itself: declaring variables, storing values, and using `typeof` are the raw material every software project moves through its phases. The construction-phase JavaScript here (variables, `let`, data types) is what the life-cycle processes shepherd from idea to running code.

SLO 2

Describe the principles of structured programming.

The section builds the structured-programming foundation: understanding what a variable holds and how types behave (dynamically typed, `null` vs `undefined`) is the careful, explicit reasoning structured programs are written with. The `typeof` operator and the type rules give the student the discipline of checking what their code actually holds.

Learning Objectives

After this section, you will be able to:

In this section, you will learn to:
  • Identify the eight basic data types in JavaScript and give an example of each.
  • Declare variables that hold different types of values and explain what "dynamically typed" means.
  • Use the typeof operator to check what type a value has.
  • Distinguish between null and undefined and use each correctly.
  • Declare variables with let and const, and explain why var is avoided.
  • Explain why decimal arithmetic is inexact, and choose safe ways to compare
  • decimals and to store money.
  • Explain why a string method never changes its string, and keep the result
  • correctly.

Every value in JavaScript has a type. A type tells us what kind of thing the value is -- a number, a piece of text, a yes/no answer, and so on. There are eight basic data types in JavaScript.

Because JavaScript is "dynamically typed," a variable can hold any type of value, and that type can change while the program runs. One moment a variable might hold a string, and the next moment it might hold a number. The variable itself is not locked to one type.

Editor
runs in your browser
▶ Press Run to see the output…

1.2.1 Number

The number type covers both whole numbers (integers) and numbers with a decimal point (floating-point).

"Dynamically typed" means the language checks types at runtime, not ahead of time. Other languages (like Java or C++) require you to declare a variable's type upfront and stick with it. JavaScript is more flexible -- but that also means type-related bugs only show up when the code actually runs.

Editor
runs in your browser
▶ Press Run to see the output…

We can do arithmetic with numbers using operators like * (multiplication), / (division), + (addition), and - (subtraction).

Definition 1.2.1: Special Numeric Values

Besides ordinary numbers, the number type includes three special values: Infinity, -Infinity, and NaN. Infinity is larger than any number. NaN stands for "Not a Number" and represents the result of an invalid math operation.

Infinity appears when we divide by zero:

Editor
runs in your browser
▶ Press Run to see the output…

We can also write Infinity directly:

Editor
runs in your browser
▶ Press Run to see the output…

NaN appears when we try to do a math operation that does not make sense:

Editor
runs in your browser
▶ Press Run to see the output…
Definition 1.2.1 — Special numeric values A number line with chips 0 through 3, joined by three special values outlined in rust: Infinity past the right end produced by 1 / 0, -Infinity past the left end, and NaN floating above the middle produced by dividing a non-numeric string by 2. Each arrives in its own beat and remains for the rest of the loop. 0 1 2 3 1 / 0 Infinity larger than any number -Infinity smaller than any number "not a number" / 2 NaN

Definition 1.2.1 — Special numeric values: Infinity, -Infinity, and NaN.

Example 1.2.1: NaN Is Sticky

Once NaN appears in a calculation, it spreads to the whole result. Any operation on NaN gives back NaN.

Build the three checks yourself -- each comment is one line to write:

Editor
runs in your browser
▶ Press Run to see the output…
Solution
Editor
runs in your browser
▶ Press Run to see the output…

Every one of them is NaN. The only exception in the whole language is NaN ** 0, which equals 1.

Math in JavaScript is "safe." The script never crashes from a bad math operation. Dividing by zero, multiplying a word by a number -- none of it stops the program. At worst, you get NaN and the code keeps running. This is different from many other languages, where such operations would halt the program with an error.

Try It Now 1.2.1

Open your browser console (F12, then click "Console"). Type each line and press Enter to see what JavaScript gives back:

10 / 3
100 / 0
"hello" * 5
Infinity + 1

Type it into the editor and run it:

Editor
runs in your browser
▶ Press Run to see the output…

What do you see for each one?

Solution

You should see:

  • 10 / 3 gives 3.3333333333333335 (a decimal result)
  • 100 / 0 gives Infinity
  • "hello" * 5 gives NaN (you cannot multiply text by a number)
  • Infinity + 1 gives Infinity (Infinity plus anything is still Infinity)
Example 1.2.2: When 0.1 Plus 0.2 Is Not 0.3

You will see 10 / 3 give 3.3333333333333335 in a moment. That trailing 5 is not a display glitch. It is how JavaScript stores decimals, and it shows up somewhere far more surprising.

Predict both lines before you run them. Write your predictions down:

Editor
runs in your browser
▶ Press Run to see the output…
Solution
Editor
runs in your browser
▶ Press Run to see the output…

Both lines are correct JavaScript doing exactly what the language specifies. 0.1 + 0.2 really is not 0.3.

The reason is the same one behind 10 / 3. JavaScript stores numbers in binary, and 0.1 has no exact binary form — its digits repeat forever, so the number is cut off. Add two cut-off numbers and the answer is slightly off.

You already accept this in decimal. Write 1/3 as a decimal and you get 0.3333..., and you have to stop somewhere. Binary stops somewhere too; it just stops at different fractions than you expect. 0.5 and 0.25 are exact in binary, because they are halves. 0.1 is not.

You can see the size of the error directly:

Editor
runs in your browser
▶ Press Run to see the output…

Not zero — but close enough that it would never matter in a measurement, and close enough that it will absolutely matter if you test it with ===.

This is not a JavaScript flaw, and changing languages does not

escape it. Java, Python, C++ and your phone's calculator all do the same thing,

because they all store decimals the same way. What differs between them is only how

many digits each one shows before rounding the display.

Two habits follow from this, and both matter later in the course:

Editor
runs in your browser
▶ Press Run to see the output…

Banking software works this way, and this is why.

Try It Now 1.2.2

Run each line. Two of the four give exactly what you would expect, and two do not.

Editor
runs in your browser
▶ Press Run to see the output…

Which two are exact? What do those two have in common?

Solution
  • 0.1 + 0.2 gives 0.30000000000000004 — not exact
  • 0.5 + 0.25 gives 0.75 — exact
  • 0.1 * 3 gives 0.30000000000000004 — not exact
  • 1.5 + 2.5 gives 4 — exact

The exact ones are built from halves and quarters. A half, a quarter and an eighth all have exact binary forms, because binary counts in halves the way decimal counts in tenths. One tenth does not.

1.2.2 BigInt

The number type cannot safely represent integers larger than 253 - 1 (which is 9007199254740991) or smaller than -(253 - 1). Beyond that range, calculations lose precision.

Editor
runs in your browser
▶ Press Run to see the output…

Notice that both results are the same number! JavaScript's number type cannot tell the difference between adding 1 and adding 2 at that size.

Definition 1.2.2: BigInt

BigInt is a data type for integers of arbitrary length. Create a BigInt by adding n to the end of an integer.

Editor
runs in your browser
▶ Press Run to see the output…
Definition 1.2.2 — number rounds off where bigint stays exact A number chip and a bigint chip side by side, both starting at 9007199254740992. Each is asked to add one. The number value flashes and does not change, because 2 to the 53rd is where a double stops counting whole numbers; the bigint value becomes 9007199254740993n exactly. Verdict notes read "rounds off" under number and "exact" under bigint, with a closing note that a bigint is written by adding n to the end of an integer. number bigint 9007199254740992 9007199254740992n 9007199254740993n +1 +1 rounds off exact add n to the end of an integer

Definition 1.2.2 — BigInt is a data type for integers of arbitrary length; add n to the end of an integer to create one.

For most everyday programming, the regular number range is plenty. But BigInt is essential for cryptography, precise timestamps, and any situation where very large integers must be exact.

Try It Now 1.2.3

In the console, try:

9007199254740991 + 3
9007199254740991n + 3n

Type it into the editor and run it:

Editor
runs in your browser
▶ Press Run to see the output…

What is different about the two results?

Solution
  • 9007199254740991 + 3 gives 9007199254740994 -- but that is wrong! The correct answer is 9007199254740994 (actually this one happens to be right by coincidence, but the precision is unreliable at this range).
  • 9007199254740991n + 3n gives 9007199254740994n -- the n suffix means BigInt handles it exactly.

The key point: once numbers get past 253 - 1, regular number math becomes unreliable. BigInt stays exact.

1.2.3 String

A string is a piece of text. In JavaScript, strings must be wrapped in quotes.

Editor
runs in your browser
▶ Press Run to see the output…
Definition 1.2.3: Three Types of Quotes

JavaScript offers three kinds of quote marks for strings:

  1. Double quotes: "Hello"
  2. Single quotes: 'Hello'
  3. Backticks: `Hello`

Double and single quotes are "simple" quotes. They work the same way. Backticks are "extended functionality" quotes -- they let us embed variables and expressions directly into a string using ${...}.

Editor
runs in your browser
▶ Press Run to see the output…

Only backticks support ${...} embedding. Double and single quotes treat ${...} as plain text -- they do not evaluate it.

The expression inside ${...} is evaluated, and the result becomes part of the string. We can put a variable like name or a calculation like 1 + 2 in there.

Editor
runs in your browser
▶ Press Run to see the output…
Definition 1.2.3 — Three types of quotes Three quote-style chips over the same embedded expression written three ways. The double-quoted and single-quoted versions are tagged as plain text and stay unchanged; the backtick version lights up and is replaced by the resolved value John, tagged as evaluating. "double" 'single' `backtick` "${name}" '${name}' `${name}` John plain text plain text evaluates simple quotes keep ${...} as plain text - backticks evaluate it

Definition 1.2.3 — Three types of quotes: double and single quotes are simple quotes that work the same way, while backticks evaluate ${...} to embed variables and expressions.

There is no separate character type in JavaScript. Some languages (like C++ or Java) have a special type for a single character. JavaScript does not. A string can hold zero characters (an empty string), one character, or many -- it is all the string type.

Try It Now 1.2.4

In the console, create a variable with your name and use backticks to print a greeting:

let myName = "Alex";
console.log(`Hello, ${myName}! Today is ${2024 + 1}.`);

Type it into the editor and run it:

Editor
runs in your browser
▶ Press Run to see the output…

Now try the same thing with single quotes instead of backticks. What happens?

Solution

With backticks, you see: Hello, Alex! Today is 2025.

With single quotes: Hello, ${myName}! Today is ${2024 + 1}. -- the ${...} is printed as literal text because single quotes do not evaluate expressions inside them.

Example 1.2.3: How Long, and Which Character

Two questions come up about a string constantly: how long is it, and what is at a particular spot. JavaScript answers both without any method call.

.length is how many characters the string contains:

Editor
runs in your browser
▶ Press Run to see the output…

Six, zero, and three. The empty string has length 0, and the space in "a b" counts — a character is a character, including the ones you cannot see.

To reach one character, put its position in square brackets. Positions start at 0, not 1:

Editor
runs in your browser
▶ Press Run to see the output…

b, a, a. The first character is at 0, so the last one is not at word.length — it is one before that:

Editor
runs in your browser
▶ Press Run to see the output…

6, then a, then undefined.

That last line is the one to remember. word[6] is not an error. There is no sixth position in a six-character string, and JavaScript answers undefined rather than complaining — the same quiet non-answer you saw from a variable that was declared and never set (Section 1.2.6 has more to say about it).

Counting from 0 looks like a nuisance and is worth getting

comfortable with now, because it is not a string quirk. Every position in

JavaScript is counted this way, and Section 3.3 will hand you a whole second

kind of value — the array — that indexes exactly the same. Learning it once

here means it is free later.

Example 1.2.4: A String Method Does Not Change Its String

A method is an action attached to a value, written with a dot after it: value.actionName(). Strings come with methods built in, and the parentheses are what run the action:

Editor
runs in your browser
▶ Press Run to see the output…

What matters here is not what toUpperCase() hands back, but what happens to city itself. Predict what this prints:

Editor
runs in your browser
▶ Press Run to see the output…
Solution

It prints ada.

Not ADA, and not an error. The line name.toUpperCase(); ran, produced "ADA", and threw it away.

Strings in JavaScript are immutable — once made, a string can never be changed. toUpperCase() cannot alter name, so it does the only thing it can: it hands back a brand-new string and leaves the original alone. If nothing catches the new string, it is discarded.

To keep it, catch it:

Editor
runs in your browser
▶ Press Run to see the output…

The rule to carry forward is that **assignment is what changes a

variable.** A method call on its own never does. Every string method in JavaScript

works this way — there is no string method anywhere that edits in place. Arrays,

which you meet in Chapter 3, have both kinds, and telling the two apart is most of

the difficulty there.

Try It Now 1.2.5

Three of these lines leave word unchanged. Predict which single line changes it, then run the block and check.

Editor
runs in your browser
▶ Press Run to see the output…
Solution

Only word = word.toLowerCase(); changes it, and the block prints stressed.

The first three lines each compute a new string and discard it, because nothing catches the result. The fourth changes word for one reason: it assigns back to word with =.

1.2.4 Boolean (Logical Type)

Definition 1.2.4: Boolean

The boolean type has exactly two values: true and false. Booleans are used to store yes/no answers.

Editor
runs in your browser
▶ Press Run to see the output…

Booleans often come from comparisons. When we ask "is 4 greater than 1?" the answer is true:

Editor
runs in your browser
▶ Press Run to see the output…
Definition 1.2.4 — Boolean A comparison, 4 greater than 1, is asked as a question and resolves to one of exactly two boolean values. Both values, true and false, are on screen the whole time; the arrow and the highlight pick out true as the answer this particular comparison produced. true yes false no ? 4 > 1 the answer is "yes"

Definition 1.2.4 — A boolean is a yes/no value: exactly two values, true and false, often produced by a comparison.

Try It Now 1.2.6

In the console, try these comparisons and see what boolean value each one produces:

10 > 5
3 < 1
"apple" === "orange"
100 === 100

Type it into the editor and run it:

Editor
runs in your browser
▶ Press Run to see the output…
Solution
  • 10 > 5 gives true
  • 3 < 1 gives false
  • "apple" === "orange" gives false
  • 100 === 100 gives true

Each comparison evaluates to either true or false.

1.2.5 The "null" Value

Definition 1.2.5: null

null is a special value that belongs to its own type. It represents "nothing," "empty," or "value unknown."

Editor
runs in your browser
▶ Press Run to see the output…
Definition 1.2.5 — null A variable slot for age that is deliberately holding the value null. The outlined slot is present from the first frame and never disappears; the null chip arrives inside it as the declaration completes, showing that null is a value occupying the slot rather than the slot being absent. Beneath the slot, 'type: null' names it as a type of its own, and the caption reads 'intentionally no value right now'. let age = null type: null intentionally no value right now

Definition 1.2.5 — null is a special value that belongs to its own type; it represents "nothing," "empty," or "value unknown."

In JavaScript, null is not a "reference to a non-existing object" (as it is in some other languages). It is simply a value that means "this variable intentionally has no value right now."

Try It Now 1.2.7

In the console, declare a variable set to null and check what typeof gives you:

let empty = null;
console.log(empty);
console.log(typeof empty);

Type it into the editor and run it:

Editor
runs in your browser
▶ Press Run to see the output…
Solution

console.log(empty) prints null. console.log(typeof empty) prints "object" -- this is a known bug in JavaScript (more on that in the typeof section). Despite what typeof says, null is not an object; it is its own separate type.

1.2.6 The "undefined" Value

Definition 1.2.6: undefined

undefined is a special value that means "value is not assigned." When you declare a variable but do not give it a value, JavaScript automatically sets it to undefined.

Editor
runs in your browser
▶ Press Run to see the output…

It is technically possible to assign undefined to a variable yourself:

Editor
runs in your browser
▶ Press Run to see the output…

Do not assign undefined yourself. Use null when you want to say "this variable is intentionally empty." Think of undefined as JavaScript's way of saying "you forgot to give this a value," and null as your way of saying "I am deliberately setting this to nothing."

Definition 1.2.6 — undefined A declared-but-unassigned variable drawn as an empty box. A question mark marks the empty slot until the word undefined drops into it, showing that JavaScript, not the programmer, supplies that value; a second note contrasts it with null, which a programmer sets deliberately. let age; ? undefined no value assigned -> JavaScript fills the slot null = your way to say "intentionally empty"

Definition 1.2.6 — undefined: the special value meaning "value is not assigned"; a declared-but-unassigned variable is automatically set to it.

Try It Now 1.2.8

In the console, declare a variable without assigning it, then check its value and type:

let futureValue;
console.log(futureValue);
console.log(typeof futureValue);

Type it into the editor and run it:

Editor
runs in your browser
▶ Press Run to see the output…
Solution

console.log(futureValue) prints undefined. console.log(typeof futureValue) prints "undefined". The variable exists, but it has no value yet -- JavaScript gave it undefined automatically.

1.2.7 Objects and Symbols

Definition 1.2.7: Primitive vs. Object Types
Definition 1.2.7 — Primitive vs. Object A still counting contrast. Six primitive-type chips each hold a single dot; one object container holds four dots in nested slots plus a trailing ellipsis. Six containers with one value each, against one container holding a collection. Primitive vs. Object primitives number string boolean null undefined bigint vs object ... a primitive holds one thing — an object holds a collection

Definition 1.2.7 - Primitive vs. Object types: primitives (number, string, boolean, null, undefined, bigint) hold a single value, while the object type stores collections of data and more complex entities.

All the types we have seen so far -- number, string, boolean, null, undefined, and bigint -- are called primitive types. A primitive value can hold only one thing (a single number, a single piece of text, a single true/false).

The object type is different. Objects can store collections of data and more complex entities. We will explore objects in depth later.

The symbol type is used to create unique identifiers, mostly for advanced object work. We will cover symbols when we discuss objects.

Try It Now 1.2.9

In the console, create a simple object and check its type:

let book = { title: "JavaScript Guide", pages: 200 };
console.log(typeof book);

Type it into the editor and run it:

Editor
runs in your browser
▶ Press Run to see the output…
Solution

console.log(typeof book) prints "object". The curly braces { } create an object that holds multiple pieces of data (a title and a page count).

1.2.8 The typeof Operator

Definition 1.2.8: typeof

The typeof operator returns a string telling us the type of a value. It is useful when we need to check what kind of data we are working with.

Editor
runs in your browser
▶ Press Run to see the output…
Definition 1.2.8 — typeof The typeof operator applied to six values. Each value chip resolves to a quoted type string beneath it, one at a time from left to right. A bug badge and a note then mark the null case, whose result is the string "object", as a historical bug kept for compatibility; a final note explains that functions are objects but typeof reports them separately. Every result is a quoted string, because typeof returns a string naming the type rather than the type itself. typeof 0 true 10n "foo" null alert "number" "boolean" "bigint" "string" "object" "function" bug null -> "object" is a famous bug, kept for compatibility functions are objects, but typeof treats them differently

Definition 1.2.8 — The typeof operator returns a string telling us the type of a value.

Three of these results need extra explanation:

  1. Math is a built-in object that provides math operations. typeof Math is "object" -- correct.
  2. typeof null is "object" -- this is wrong. It is a famous bug in JavaScript from the very early days, kept for compatibility. null is not an object; it is its own type.
  3. typeof alert is "function" -- alert is a function. There is no special "function" type in JavaScript; functions are a kind of object. But typeof treats them differently and returns "function".

The typeof(x) syntax: You might also see typeof written with parentheses, like typeof(x). This is the same as typeof x. The parentheses are not part of typeof -- typeof is an operator, not a function. The parentheses are just for grouping, like in math.

Try It Now 1.2.10

In the console, use typeof to check the type of several different values:

typeof "hello"
typeof 42
typeof true
typeof undefined
typeof null
typeof { name: "Sarah" }

Type it into the editor and run it:

Editor
runs in your browser
▶ Press Run to see the output…

Which result is surprising?

Solution
  • typeof "hello" gives "string"
  • typeof 42 gives "number"
  • typeof true gives "boolean"
  • typeof undefined gives "undefined"
  • typeof null gives "object" -- this is the surprising one! It is a known bug.
  • typeof { name: "Sarah" } gives "object"

1.2.9 Declaring a Variable

Every code block so far has begun a line with let. This section is what that word has been doing.

A variable is a named box. Declaring it makes the box; assigning puts something in.

Editor
runs in your browser
▶ Press Run to see the output…
Definition 1.2.9: let, const, and var

JavaScript has three words for making a variable.

  • let makes a variable you can reassign later.
  • const makes one you cannot reassign. Use it whenever the value should not

change — which is most of the time. - var is the original keyword from 1995. It still works, and you will meet it in older code, but it behaves differently in a way that caused years of bugs. Do not write new code with it.

Editor
runs in your browser
▶ Press Run to see the output…

Reassigning a const is one of the few things in this section that stops the program outright:

Editor
runs in your browser
▶ Press Run to see the output…
Definition 1.2.9 — let, const, and var A dashed block containing three declarations, each lighting in turn with its reassignment verdict, and a second panel outside the block where only the var declaration is still visible, reached by an arrow crossing the block boundary. inside the block after the block ends { } let count = 1; count = 5 — ok const pi = 3.14; pi = 3 TypeError var total = 1; total = 5 — ok count — not defined pi — not defined total still here let and const stop at the brace. var does not.

Definition 1.2.9 — let makes a variable you can reassign, const one you cannot, and var the 1995 keyword that ignores block boundaries. let and const stop at the closing brace; var does not.

Example 1.2.5: Where var Leaks

A pair of braces { } marks off a block — a section of code treated as one unit. Blocks are what if statements and loops will be built from in Chapter 2.

Here is the difference between let and var, and the reason let was added to the language. Predict what each console.log prints:

Editor
runs in your browser
▶ Press Run to see the output…
Solution

The first prints undefined — outside the block, inner does not exist at all.

The second prints stringouter escaped the block and is still there.

let is block-scoped: it exists only between the braces that declared it. var

is function-scoped: it ignores blocks entirely and leaks out to the surrounding code. That is the whole difference, and it was enough of one that let was added in 2015 specifically to fix it.

The leak matters most inside loops, because a loop body is a

block. A var counter declared in a loop is still readable after the loop ends,

still holding its last value. Code that reads it by accident looks correct and runs

without complaint.

Example 1.2.6: The Variable You Never Declared

One more hazard, and this one needs no var at all — only a forgotten let. Predict what this prints:

Editor
runs in your browser
▶ Press Run to see the output…
Solution

It prints 100.

Assigning to a name that was never declared does not fail. JavaScript creates the variable for you, at the outermost level of the program, where every other piece of code can see it and overwrite it.

A variable meant to stay inside one small piece of code is now visible to the whole program. Nothing warns you. The bug surfaces later, somewhere else, when a second piece of code uses the same ordinary name — tally, count, total — and the two quietly overwrite each other.

The fix is one line at the top of the file:

Editor
runs in your browser
▶ Press Run to see the output…

"use strict" turns the silent accident into an immediate error that names the line.

Notice the pattern, not just the rule. The dangerous version of

this bug is not the one that crashes — it is the one that works. A program that runs

and produces a wrong answer gives you nothing to search for. Strict mode is the

first of several tools in this course whose whole job is to turn a silent wrong

answer into a loud one.

Strict mode catches the string case from §1.2.3 too — the method call that seemed to do nothing:

Editor
runs in your browser
▶ Press Run to see the output…

That one was never an error, only a discarded result. Strict mode does not rescue a thrown-away value; nothing can. Catching it with = is the only fix, which is why the habit matters more than the tooling.

Try It Now 1.2.11

Predict the output of each block before running it. One of the three stops with an error.

Editor
runs in your browser
▶ Press Run to see the output…
Solution
  • Block 1 prints 1. The inner x is a separate variable that exists only inside
  • the braces. The outer x was never touched.
  • Block 2 prints 2. var ignores the braces, so there is only one y, and the
  • inner line overwrote it.
  • Block 3 stops with TypeError: Assignment to constant variable.

Block 1 and Block 2 are the same code with one word changed, and they give different answers. That is the reason to write let.

Summary

There are 8 basic data types in JavaScript.

Seven primitive data types (each holds a single value):

One non-primitive data type:

The typeof operator tells us which type a value has. Use it as typeof x or typeof(x). It returns a string like "string" or "number". Note: typeof null returns "object" -- this is a bug in JavaScript, not the actual type of null.

Problem Set 1.2

1.2.1 What does it mean that JavaScript is "dynamically typed"? Give an example.

Solution

Step 1 — Understanding what "typed" means: In some languages (like Java or C), when you create a variable you must declare what kind of data it holds — a number, text, a true/false value — and it can never hold anything else. JavaScript does not work that way.

Step 2 — What "dynamically" changes this: JavaScript decides the type of a variable from the value it currently holds, at the moment the code runs. The same variable can hold a number right now and text a moment later.

Answer: "Dynamically typed" means a variable's type is determined by the value stored in it at runtime, not fixed by the programmer ahead of time. For example:

Editor
runs in your browser
▶ Press Run to see the output…

1.2.2 What are the three special numeric values in JavaScript? How does each one appear?

Solution

Step 1 — The first two special values: Infinity and -Infinity are numeric values that stand for "larger than any real number" and "smaller than any real number." They appear when math overflows, like 1 / 0, or when a number grows too big to be stored.

Step 2 — The third special value: NaN stands for "Not a Number." It is still a number-type value, but it appears when a math operation fails to produce a valid number — for example, "hello" * 3 or 0 / 0.

Answer: The three special numeric values are:

  • Infinity — appears from 1 / 0 or numbers too large to represent.
  • -Infinity — appears from -1 / 0 or numbers too negatively large.
  • NaN ("Not a Number") — appears when a numeric operation has no valid result, such as "abc" - 5 or 0 / 0.

1.2.3 What is the difference between null and undefined? When would you use each one?

Solution

Step 1 — What each one represents: undefined is JavaScript's automatic "no value yet" marker. If you declare a variable and never assign it anything, its value is undefined. null, on the other hand, is a value you choose to assign — it means "I am deliberately setting this to nothing."

Step 2 — Deciding which to use: You never assign undefined on purpose — JavaScript supplies it. You use null when you want to say "this slot exists but is intentionally empty right now" — for example, a form field for a middle name that the person does not have.

Answer: undefined means a variable was declared but never given a value (JavaScript's default "empty" state). null is an explicit value a programmer assigns to say "intentionally empty." Use null when you want to mark something as empty on purpose; use undefined when you want to detect that something was never set:

Editor
runs in your browser
▶ Press Run to see the output…

1.2.4 What will the following code print?

Editor
runs in your browser
▶ Press Run to see the output…
Solution

Step 1 — Trace the first line: let x = 10; creates a variable named x and stores the number 10 in it.

Step 2 — Trace the second and third lines: The next line, x = "ten";, overwrites that number with the text "ten" — no let again, because the variable already exists. This works thanks to dynamic typing. Finally, console.log(x); prints whatever x holds now, which is the string "ten".

Answer: The code prints ten. Because JavaScript is dynamically typed, reassigning x from a number to a string is perfectly legal:

Editor
runs in your browser
▶ Press Run to see the output…

1.2.5 What is the result of typeof "hello"? What about typeof 42? What about typeof null?

Solution

Step 1 — The typeof operator: typeof is a built-in operator that answers the question "what type of value is this?" It returns a string naming the type.

Step 2 — Check each value:

  • typeof "hello" — the quotes mark a string, so the result is the string "string".
  • typeof 42 — a plain number, so the result is "number".
  • typeof null — here is the surprise: null is technically its own primitive type, but the operator reports "object".

Answer:

Editor
runs in your browser
▶ Press Run to see the output…

The null result is a historical bug from the language's first version. It was never fixed because too much existing code depended on it, so typeof null still reports "object" today even though null is not an object.

1.2.6 Explain why NaN + 1 equals NaN.

Solution

Step 1 — What NaN means: NaN ("Not a Number") is the result JavaScript produces when an arithmetic operation has no meaningful numeric answer — for instance, "hello" - 3. It is not a special error message; it is a value that flows through your code like any other number.

Step 2 — Why the result stays NaN: Arithmetic with NaN cannot recover a real number, because the bad value has already poisoned the computation. Adding 1 to "not a number" still gives "not a number" — garbage in, garbage out. This is called propagation.

Answer: NaN + 1 equals NaN because once a computation contains a non-numeric result, every further operation on it remains non-numeric. The "badness" spreads through the math:

Editor
runs in your browser
▶ Press Run to see the output…

1.2.7 What is the difference between backtick strings and double-quote strings in JavaScript?

Solution

Step 1 — What double quotes do: A double-quoted string (like "Hello") is a plain, literal piece of text. What you write is exactly what you get — no way to insert the value of a variable or a calculation into the middle of it.

Step 2 — What backticks add: Backtick strings (like `Hello`), called template literals, can embed expressions directly using ${...}. Whatever expression you place inside the curly braces is evaluated and inserted into the text. They also allow the string to span multiple lines.

Answer: Backtick strings (template literals) support embedded expressions with ${...} and multi-line text; double-quoted strings are plain text only. Example:

Editor
runs in your browser
▶ Press Run to see the output…

1.2.8 What is a BigInt, and when would you use one instead of a regular number?

Solution

Step 1 — The limit of regular numbers: Regular JavaScript numbers cannot safely represent integers beyond about 9 quadrillion (2⁵³ − 1). Beyond that, the computer silently rounds, so two different huge numbers can become the same value — a precision error.

Step 2 — What BigInt changes: A BigInt is a number type that can represent integers of any size, exactly. You create one by appending n to a number (like 12345678901234567890n). BigInts can only hold whole numbers, never decimals, and mixing a BigInt with a regular number in arithmetic is not allowed.

Answer: A BigInt is an integer type with no size limit, written with a trailing n:

Editor
runs in your browser
▶ Press Run to see the output…

Use it whenever you work with integers larger than 9,007,199,254,740,991 (2⁵³ − 1) — for example, counting stars, astronomical distances, or database IDs that exceed that bound — where regular numbers would lose precision.

1.2.9 What will this code output?

Editor
runs in your browser
▶ Press Run to see the output…
Solution

Step 1 — Declaring without assigning: let a; creates a variable named a but never gives it a value. The variable exists — it just holds nothing yet.

Step 2 — JavaScript's automatic default: When a declared variable has not been assigned, JavaScript automatically gives it the special value undefined (meaning "no value was ever set"). So console.log(a); prints that default value.

Answer: The code outputs undefined:

Editor
runs in your browser
▶ Press Run to see the output…

No error occurs — an unassigned variable is perfectly legal in JavaScript; it simply holds the default value undefined.

1.2.10 Name the seven primitive data types in JavaScript.

Solution

Step 1 — Group the basic types: The seven primitive types are the "building blocks" of data in JavaScript. Start with the three value families: text, numbers, and true/false. Numbers split into two: ordinary numbers and BigInt. Then add the two "empty" values, and finally the newest member, symbols.

Step 2 — Check the list against what you know:

  • string — text, in quotes or backticks.
  • number — ordinary numbers, including Infinity and NaN.
  • bigint — huge integers with an n.
  • booleantrue or false.
  • undefined — declared but never assigned.
  • null — deliberately empty.
  • symbol — a unique, unchangeable identifier (rarely used by beginners, but it is a primitive).

Answer: The seven primitive data types in JavaScript are: string, number, bigint, boolean, undefined, null, and symbol. You can verify any of them with typeof (with the known null quirk):

Editor
runs in your browser
▶ Press Run to see the output…

Key Terms

Term Definition
BigInt A data type for integers of arbitrary length, created by appending n to a number.
block A section of code between { and }, treated as one unit.
block scope The rule that a variable exists only inside the block that declared it. let and const follow it; var does not.
boolean A data type with only two values: true and false.
data type A classification of data that tells the language what kind of value a variable holds.
declare To create a named variable with let, const, or var.
dynamically typed A property of a language where variables are not bound to a single type; the type can change at runtime.
immutable Cannot be changed after it is created. Every JavaScript string is immutable; changing one means building a new one and assigning it back.
method An action attached to a value, written value.actionName(). Sharpened once objects arrive, in Definition 3.5.3.
NaN A special numeric value meaning "Not a Number," produced by invalid math operations.
null A special value representing "nothing," "empty," or "value unknown."
number A data type for integers and floating-point numbers, including special values Infinity and NaN.
object A non-primitive data type that stores collections of data and complex entities.
primitive type A data type whose values can contain only a single thing (e.g., number, string, boolean).
strict mode A setting turned on by "use strict" that reports several mistakes JavaScript otherwise ignores.
string A data type for text, enclosed in quotes.
typeof An operator that returns a string naming the type of a value.
undefined A special value automatically assigned to variables that have been declared but not given a value.

Table: Table 1.2.1 — Key terms introduced in this section, with their definitions.