JavaScript
Types
Master the six fundamental data types in JavaScript: number, string, boolean, null, undefined, and object: the building blocks of every program.
What Are Data Types?
Every value in JavaScript has a type. A type tells the engine what kind of data you are working with and what operations are valid on it. Think of types as labels on containers: the label determines what you can put inside and what you can do with the contents.
Discovering Types with typeof
JavaScript provides the typeof operator to inspect a value's type at runtime. It returns a string describing the type.
Why Types Matter
The JavaScript Type Family
Primitives vs Objects
| Primitives | Objects | |
|---|---|---|
| Examples | 42, "hi", true | {}, [], function |
| Mutability | Immutable | Mutable |
| Compared by | Value | Reference |
| typeof | Returns own type | Returns "object" |
| Can hold properties? | No | Yes |
The Number Type
JavaScript has one number type for both integers and decimals. Under the hood, all numbers are 64-bit floating point (IEEE 754).
The String Type
Strings represent text. They can be created with single quotes, double quotes, or backticks (template literals).
The Boolean Type
Booleans have exactly two values: true and false. They are the backbone of every if statement, loop, and conditional expression.
null vs undefined
The Object Type
Objects store collections of key-value pairs. Arrays and functions are specialized objects. Objects are mutable and compared by reference.
How to Check Types
Example: Identifying Types
For each value, predict the result of typeof:
Example: Type Coercion
JavaScript silently converts types in mixed expressions. Predict each result and its type:
Example: Value vs Reference
Common Mistakes
Type Summary
| Type | typeof Result | Example | Falsy? |
|---|---|---|---|
| number | "number" | 42, 3.14, NaN | 0, NaN |
| string | "string" | "hello", "" | "" |
| boolean | "boolean" | true, false | false |
| null | "object" | null | null |
| undefined | "undefined" | undefined | undefined |
| object | "object" | {}, [] | Never |
Question 1 of 5
What does typeof "42" return?
Question 2 of 5
What is the result of "5" + 3 in JavaScript?
Question 3 of 5
Which of the following correctly checks if a variable x is null?
Question 4 of 5
What is the difference between null and undefined?
Question 5 of 5
Given the code below, what does console.log(obj1.val) print?
let obj1 = { val: 10 };
let obj2 = obj1;
obj2.val = 99;
console.log(obj1.val);