Data Types
JavaScript has several built-in data types. Understanding them is crucial for writing effective code.
Primitive Types (immutable, stored by value):
-
String - Text data enclosed in quotes
- Single quotes: 'Hello'
- Double quotes: "Hello"
- Template literals:
Hello ${name}
-
Number - Both integers and decimals
- Integers: 42, -17, 0
- Decimals: 3.14, -0.5
- Special values: Infinity, -Infinity, NaN
-
Boolean - True or false values
- true, false
- Result of comparisons: 5 > 3 (true)
-
undefined - Variable declared but not assigned
-
null - Intentional absence of value
-
Symbol - Unique identifier (ES6+)
-
BigInt - Large integers (ES2020+)
Reference Types (mutable, stored by reference):
- Object - Collection of key-value pairs
- Array - Ordered list of values
- Function - Reusable block of code
Use typeof operator to check the type of a value.
Code Examples
// String - text data
let greeting = "Hello, World!";
let name = 'Alice';
let message = `Welcome, ${name}!`; // Template literal
// Number - integers and decimals
let age = 25;
let price = 19.99;
let negative = -42;
let infinity = Infinity;
let notANumber = NaN;
// Boolean - true/false
let isActive = true;
let isComplete = false;
let isGreater = 10 > 5; // true
// undefined and null
let notDefined; // undefined (not assigned)
let empty = null; // null (intentionally empty)
// Check types with typeof
console.log(typeof greeting); // "string"
console.log(typeof age); // "number"
console.log(typeof isActive); // "boolean"
console.log(typeof notDefined); // "undefined"
console.log(typeof empty); // "object" (historical bug)Primitive types are immutable - operations on them create new values rather than modifying the original.
// Object - key-value pairs
let person = {
name: "Alice",
age: 30,
isStudent: false,
greet: function() {
console.log("Hello, I'm " + this.name);
}
};
console.log(person.name); // "Alice"
console.log(person["age"]); // 30
person.greet(); // "Hello, I'm Alice"
// Array - ordered list
let colors = ["red", "green", "blue"];
console.log(colors[0]); // "red"
console.log(colors.length); // 3
// Arrays can hold mixed types
let mixed = [42, "hello", true, null, { key: "value" }];
// Function - reusable code
function add(a, b) {
return a + b;
}
console.log(add(5, 3)); // 8
console.log(typeof add); // "function"Reference types are stored by reference, meaning multiple variables can point to the same object in memory.
Quick Quiz
1. What is the result of typeof null in JavaScript?
2. Which of these is NOT a primitive type in JavaScript?
Was this lesson helpful?