JavaScript Data Types
Explore JavaScript primitive types: strings, numbers, booleans, and more.
JavaScript is a dynamically typed language with several built-in data types. Understanding these types is essential for writing effective code and avoiding common bugs. From strings and numbers to the special values null and undefined, each type has unique behaviors and use cases. This exercise explores the fundamental data types you'll work with every day.
📚 Concepts & Theory
Primitive Data Types:
String - Text data:
let greeting = "Hello, World!";
let name = 'Alice';
let template = Hello, !; // Template literal
Number - Integers and decimals:
let age = 25;
let price = 19.99;
let negative = -10;
let infinity = Infinity;
let notANumber = NaN;
Boolean - True or false:
let isActive = true;
let isComplete = false;
Undefined - Variable declared but not assigned:
let x;
console.log(x); // undefined
Null - Intentional absence of value:
let user = null; // Explicitly "no value"
Checking Types:
typeof "hello" // "string"
typeof 42 // "number"
typeof true // "boolean"
typeof undefined // "undefined"
typeof null // "object" (quirk!) 🎯 Your Challenge
Create variables for each data type: a string `productName` with "Laptop", a number `price` with 999.99, a boolean `inStock` with true, and a variable `discount` that is null.
📝 Starter Code
// String
let productName =
// Number
let price =
// Boolean
let inStock =
// Null
let discount =
- Strings need quotes, numbers don't
- Booleans are true or false (lowercase)
- null means "intentionally empty"
- undefined means "not yet assigned"
Solution
let productName = "Laptop";
let price = 999.99;
let inStock = true;
let discount = null;
Explanation
We create a string using quotes, a number without quotes (including decimals), a boolean with the literal true, and null to represent an intentional absence of a value for discount. Each variable uses let because values might change later.
⚠️ Common Mistakes to Avoid
- Putting numbers in quotes (makes them strings)
- Confusing null and undefined
- Using NULL or True (wrong case)
- Forgetting that typeof null returns object