Data types define what kind of value a variable holds. Is it text? A number? True or false? JavaScript has several built-in data types, and understanding them is crucial for writing effective code. Let's explore each type and learn how to work with them!
What Are Data Types?
A data type specifies what kind of value a variable contains. Different types of data behave differently and support different operations.
// Different data types
let name = "John"; // String (text)
let age = 25; // Number
let isStudent = true; // Boolean (true/false)
let score = null; // Null (intentionally empty)
let address; // Undefined (not assigned yet)JavaScript is dynamically typed, meaning you don't need to declare what type a variable is—JavaScript figures it out automatically.
// The same variable can hold different types
let value = 42; // Number
console.log(typeof value); // "number"
value = "Hello"; // Now it's a string
console.log(typeof value); // "string"
value = true; // Now it's a boolean
console.log(typeof value); // "boolean"Primitive vs Reference Types
JavaScript data types fall into two categories:
Primitive Types (7 types)
Simple, immutable values stored directly in the variable. When you copy them, you get a separate copy.
- String
- Number
- Boolean
- Null
- Undefined
- Symbol (ES6+)
- BigInt (ES2020+)
Reference Types (Objects)
Complex values that can hold multiple values. When you copy them, you copy a reference, not the value itself.
- Objects
- Arrays
- Functions
Key Difference: Primitive types are copied by value. Reference types are copied by reference. We'll explore this difference in detail later.
String Type
Strings represent text. You can create them with single quotes, double quotes, or backticks (template literals).
Creating Strings
// Three ways to create strings
let single = 'Hello';
let double = "Hello";
let template = `Hello`;
// All are equivalent
console.log(single); // Hello
console.log(double); // Hello
console.log(template); // HelloString Characteristics
let message = "Hello, World!";
// Strings have a length property
console.log(message.length); // 13
// You can access individual characters (zero-indexed)
console.log(message[0]); // H
console.log(message[7]); // W
// Strings are immutable (can't be changed)
message[0] = "h"; // This doesn't work
console.log(message); // Still "Hello, World!"
// You must create a new string to "change" it
message = "hello, world!"; // This works (new string)
console.log(message); // hello, world!Special Characters
// Escape sequences
let newLine = "First line\nSecond line";
let tab = "Name\tAge";
let quote = "She said, \"Hello\"";
let backslash = "C:\\Users\\John";
console.log(newLine);
// First line
// Second line
console.log(tab); // Name Age
console.log(quote); // She said, "Hello"
console.log(backslash); // C:UsersJohnTemplate Literals (Backticks)
let name = "John";
let age = 25;
// Template literals allow embedded expressions
let greeting = `Hello, my name is ${name} and I'm ${age} years old.`;
console.log(greeting);
// Multi-line strings (no \n needed)
let multiLine = `
This is line 1
This is line 2
This is line 3
`;
console.log(multiLine);
// Can include expressions
let price = 50;
let quantity = 3;
let total = `Total: $${price * quantity}`;
console.log(total); // Total: $150String Practice
Experiment with different string operations
console.log() to see your output in the console above.Number Type
JavaScript has a single number type that represents both integers and floating-point numbers.
Number Basics
// Integers
let age = 25;
let score = 100;
// Floating-point numbers (decimals)
let price = 19.99;
let pi = 3.14159;
// Negative numbers
let temperature = -5;
let balance = -150.50;
// Scientific notation
let large = 1e6; // 1,000,000
let small = 1e-6; // 0.000001
console.log(large); // 1000000
console.log(small); // 0.000001Special Number Values
// Infinity
console.log(1 / 0); // Infinity
console.log(-1 / 0); // -Infinity
console.log(Infinity + 1); // Infinity
// NaN (Not a Number)
console.log(0 / 0); // NaN
console.log("hello" * 2); // NaN
console.log(Math.sqrt(-1)); // NaN
// Checking for NaN
let result = "hello" * 2;
console.log(isNaN(result)); // true
console.log(isNaN(42)); // falseNumber Methods
let num = 123.456;
// Convert to string
console.log(num.toString()); // "123.456"
// Fixed decimal places
console.log(num.toFixed(2)); // "123.46"
console.log(num.toFixed(0)); // "123"
// Parse numbers from strings
console.log(parseInt("123")); // 123
console.log(parseInt("123.456")); // 123 (truncates)
console.log(parseFloat("123.456")); // 123.456
// Number conversion
console.log(Number("123")); // 123
console.log(Number("123.456")); // 123.456
console.log(Number("hello")); // NaNMath Operations
// Basic arithmetic
console.log(10 + 5); // 15 (addition)
console.log(10 - 5); // 5 (subtraction)
console.log(10 * 5); // 50 (multiplication)
console.log(10 / 5); // 2 (division)
console.log(10 % 3); // 1 (remainder/modulo)
console.log(2 ** 3); // 8 (exponentiation)
// Order of operations (PEMDAS)
console.log(2 + 3 * 4); // 14 (not 20)
console.log((2 + 3) * 4); // 20 (parentheses first)
// Increment and decrement
let count = 5;
count++; // Add 1
console.log(count); // 6
count--; // Subtract 1
console.log(count); // 5Floating-Point Precision: Computers can't always represent decimal numbers exactly. This can lead to small errors:
console.log(0.1 + 0.2); // 0.30000000000000004 (not exactly 0.3!)
// For money calculations, work in cents
let price = 1050; // $10.50 in cents
let total = price * 2;
console.log(total / 100); // 21 (convert back to dollars)Boolean Type
Booleans represent logical values: true or false. They're essential for making decisions in your code.
Boolean Basics
// Boolean values
let isLoggedIn = true;
let isAdmin = false;
let hasPermission = true;
console.log(isLoggedIn); // true
console.log(typeof isLoggedIn); // "boolean"
// Booleans from comparisons
let age = 18;
let isAdult = age >= 18;
console.log(isAdult); // true
let score = 75;
let passed = score >= 60;
console.log(passed); // trueBoolean in Conditions
let isRaining = true;
if (isRaining) {
console.log("Take an umbrella!");
} else {
console.log("Enjoy the sunshine!");
}
// Negating with !
let isSunny = !isRaining;
console.log(isSunny); // falseTruthy and Falsy Values
In JavaScript, values can be converted to boolean. Some values are "falsy" (become false), others are "truthy" (become true).
Falsy values (only 6):
false0(zero)""(empty string)nullundefinedNaN
Truthy values: Everything else!
- All numbers except 0 (including negative numbers)
- All strings except empty string (even "0" or "false")
- All objects and arrays
- The boolean true
// Falsy values
console.log(Boolean(false)); // false
console.log(Boolean(0)); // false
console.log(Boolean("")); // false
console.log(Boolean(null)); // false
console.log(Boolean(undefined)); // false
console.log(Boolean(NaN)); // false
// Truthy values
console.log(Boolean(true)); // true
console.log(Boolean(1)); // true
console.log(Boolean(-1)); // true
console.log(Boolean("hello")); // true
console.log(Boolean("0")); // true (string, not number!)
console.log(Boolean([])); // true
console.log(Boolean({})); // trueNull and Undefined
These two types represent "no value," but they're used in different situations.
Undefined
undefined means a variable has been declared but not assigned a value. JavaScript sets this automatically.
// Variable declared but not assigned
let name;
console.log(name); // undefined
console.log(typeof name); // "undefined"
// Function with no return
function test() {
// No return statement
}
console.log(test()); // undefined
// Non-existent object property
let person = { age: 25 };
console.log(person.name); // undefinedNull
null is an intentional assignment meaning "no value" or "empty." You set this yourself.
// Intentionally setting to null
let result = null;
console.log(result); // null
console.log(typeof result); // "object" (this is a JavaScript bug!)
// Common use: reset a variable
let user = { name: "John" };
user = null; // Clear the user
// Checking for null
if (result === null) {
console.log("Result is null");
}Null vs Undefined
// undefined: JavaScript says "I don't know what this is yet"
let notAssigned;
console.log(notAssigned); // undefined
// null: You say "this is intentionally empty"
let intentionallyEmpty = null;
console.log(intentionallyEmpty); // null
// Comparison
console.log(null == undefined); // true (loose equality)
console.log(null === undefined); // false (strict equality)
// Best practice: use null when you want to explicitly set "no value"
let selectedItem = null; // No item selected yet
// Let JavaScript use undefined for uninitialized variables
let tempValue; // Don't set to undefined manuallyRule of Thumb: Use null when you want to explicitly indicate "no value." Let JavaScript handle undefined for uninitialized variables.
The typeof Operator
The typeof operator tells you what type a value is. It returns a string describing the type.
Using typeof
// Checking types
console.log(typeof "hello"); // "string"
console.log(typeof 42); // "number"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof null); // "object" (JavaScript bug!)
console.log(typeof {}); // "object"
console.log(typeof []); // "object" (arrays are objects)
console.log(typeof function() {}); // "function"Practical typeof Usage
function processValue(value) {
if (typeof value === "string") {
console.log("Processing string:", value.toUpperCase());
} else if (typeof value === "number") {
console.log("Processing number:", value * 2);
} else if (typeof value === "boolean") {
console.log("Processing boolean:", !value);
} else {
console.log("Unknown type:", typeof value);
}
}
processValue("hello"); // Processing string: HELLO
processValue(42); // Processing number: 84
processValue(true); // Processing boolean: falsetypeof Quirks
Be aware of these typeof quirks:
// null returns "object" (this is a bug)
console.log(typeof null); // "object" (should be "null")
// Arrays return "object"
console.log(typeof [1, 2, 3]); // "object"
// To check for array, use Array.isArray()
console.log(Array.isArray([1, 2, 3])); // true
console.log(Array.isArray({})); // false
// NaN is a number!
console.log(typeof NaN); // "number"Type Inspector
See the variables, their types, and values in real-time
let text = "Hello World";
let number = 42;
let decimal = 3.14;
let yes = true;
let no = false;
let nothing = null;
let notDefined;
let calculation = 10 * 5;No variables detected. Declare some variables in the code above.
let, const, or var keywords.Objects and Arrays (Introduction)
Objects and arrays are reference types that can hold multiple values. We'll cover them in depth in later lessons, but here's a quick introduction.
Objects
Objects store collections of key-value pairs (properties).
// Creating an object
let person = {
name: "John",
age: 25,
city: "New York"
};
console.log(person);
console.log(typeof person); // "object"
// Accessing properties
console.log(person.name); // "John"
console.log(person.age); // 25Arrays
Arrays store ordered lists of values.
// Creating an array
let colors = ["red", "green", "blue"];
console.log(colors);
console.log(typeof colors); // "object"
console.log(Array.isArray(colors)); // true
// Accessing elements (zero-indexed)
console.log(colors[0]); // "red"
console.log(colors[1]); // "green"
console.log(colors[2]); // "blue"Comparing Data Types
// Strings
let str1 = "hello";
let str2 = "hello";
console.log(str1 === str2); // true (same value)
// Numbers
let num1 = 42;
let num2 = 42;
console.log(num1 === num2); // true (same value)
// Booleans
let bool1 = true;
let bool2 = true;
console.log(bool1 === bool2); // true (same value)
// Different types
console.log(5 === "5"); // false (different types)
console.log(5 == "5"); // true (loose equality converts types)
// Always use === (strict equality)
console.log(0 === false); // false
console.log(0 == false); // true (loose equality)
console.log("" === false); // false
console.log("" == false); // true (loose equality)Best Practice: Always use === (strict equality) instead of == (loose equality). Strict equality doesn't convert types, making your code more predictable.
Practical Examples
Example 1: User Registration
// User data with different types
let userName = "john_doe"; // string
let email = "john@example.com"; // string
let age = 25; // number
let isVerified = false; // boolean
let profilePicture = null; // null (no picture yet)
let lastLogin; // undefined (never logged in)
console.log("Username:", userName, typeof userName);
console.log("Email:", email, typeof email);
console.log("Age:", age, typeof age);
console.log("Verified:", isVerified, typeof isVerified);
console.log("Profile pic:", profilePicture, typeof profilePicture);
console.log("Last login:", lastLogin, typeof lastLogin);Example 2: Shopping Cart
// Shopping cart with various types
let productName = "Laptop"; // string
let productPrice = 999.99; // number
let quantity = 2; // number
let inStock = true; // boolean
let discount = null; // null (no discount)
let shippingAddress; // undefined (not provided)
// Calculate total
let subtotal = productPrice * quantity;
let hasDiscount = discount !== null;
console.log(`Product: ${productName}`);
console.log(`Price: $${productPrice}`);
console.log(`Quantity: ${quantity}`);
console.log(`Subtotal: $${subtotal}`);
console.log(`In stock: ${inStock}`);
console.log(`Has discount: ${hasDiscount}`);Student Profile Example
See different data types in action
console.log() to see your output in the console above.Key Takeaways
- JavaScript has 7 primitive types: string, number, boolean, null, undefined, symbol, bigint
- Reference types include objects, arrays, and functions
- Strings represent text and can be created with quotes or backticks
- Numbers include both integers and decimals (floats)
- Booleans are either
trueorfalse nullis intentionally empty,undefinedmeans not yet assigned- Use
typeofto check a value's type typeof nullreturns "object" (this is a JavaScript quirk)- Always use
===for comparisons (strict equality) - Falsy values: false, 0, "", null, undefined, NaN
- Everything else is truthy
What's Next?
You now understand the fundamental data types in JavaScript and how to check what type a value is. This knowledge is crucial—every variable you create will be one of these types!
In the next lesson, we'll learn about Comments and Code Organization—how to document your code effectively and keep it clean and readable as your programs grow more complex.
💪 Practice Challenge:
Before moving on, try this:
- Create variables of each primitive type (string, number, boolean, null, undefined)
- Use
typeofto check each variable's type - Create an object with at least 5 properties of different types
- Experiment with truthy and falsy values using
Boolean() - Practice converting between types (string to number, number to string)
Test Your Understanding
What data type is the value 42?
let age = 42;