Data Types
Data types define what kind of data can be stored and manipulated within a program. JavaScript is dynamically typed, meaning variables can hold different types of data and can change types during runtime.
JavaScript Type System
JavaScript has two main categories of data types:
1. Primitive Types (7 types)
- •Number: Integers and floating-point numbers
- •String: Text data
- •Boolean: true or false values
- •Undefined: Variable declared but not assigned
- •Null: Intentional absence of value
- •Symbol: Unique identifiers (ES6+)
- •BigInt: Large integers (ES2020+)
2. Non-Primitive Types (Reference Types)
- •Object: Collections of key-value pairs
- •Array: Ordered lists (special type of object)
- •Function: Reusable code blocks (special type of object)
Primitive Data Types
1. Number
JavaScript has only one number type that represents both integers and floating-point numbers:
javascript// Integers let age = 25; let score = 100; let temperature = -5; // Floating-point numbers let price = 99.99; let pi = 3.14159; let percentage = 0.85; // Scientific notation let bigNumber = 1.5e6; // 1,500,000 let smallNumber = 2.5e-4; // 0.00025 // Special numeric values let infinity = Infinity; let negativeInfinity = -Infinity; let notANumber = NaN; // "Not a Number" console.log(typeof age); // "number" console.log(typeof price); // "number" console.log(typeof infinity); // "number" console.log(typeof NaN); // "number" (confusing but true!)
Working with Numbers
javascript// Basic arithmetic let a = 10; let b = 3; console.log(a + b); // 13 (addition) console.log(a - b); // 7 (subtraction) console.log(a * b); // 30 (multiplication) console.log(a / b); // 3.333... (division) console.log(a % b); // 1 (remainder/modulo) console.log(a ** b); // 1000 (exponentiation) // Increment and decrement let counter = 5; counter++; // 6 (post-increment) ++counter; // 7 (pre-increment) counter--; // 6 (post-decrement) --counter; // 5 (pre-decrement) // Number methods let num = 123.456; console.log(num.toFixed(2)); // "123.46" console.log(num.toPrecision(4)); // "123.5" console.log(parseInt("123.45")); // 123 console.log(parseFloat("123.45")); // 123.45 // Checking for valid numbers console.log(isNaN("hello")); // true console.log(isFinite(100)); // true console.log(isFinite(Infinity)); // false
2. String
Strings represent text data and can be created using single quotes, double quotes, or template literals:
javascript// Different ways to create strings let singleQuotes = 'Hello World'; let doubleQuotes = "Hello World"; let templateLiteral = `Hello World`; // Strings with quotes inside let message1 = "It's a beautiful day"; let message2 = 'He said "Hello"'; let message3 = `She said "It's amazing!"`; // Multi-line strings (template literals) let multiLine = ` This is a multi-line string `; // String interpolation (template literals) let name = "John"; let age = 25; let greeting = `Hello, my name is ${name} and I'm ${age} years old.`; console.log(greeting); // "Hello, my name is John and I'm 25 years old."
String Properties and Methods
javascriptlet text = "JavaScript is awesome!"; // Properties console.log(text.length); // 21 // Case methods console.log(text.toUpperCase()); // "JAVASCRIPT IS AWESOME!" console.log(text.toLowerCase()); // "javascript is awesome!" // Search methods console.log(text.indexOf("Script")); // 4 console.log(text.includes("Java")); // true console.log(text.startsWith("Java")); // true console.log(text.endsWith("some!")); // true // Extraction methods console.log(text.substring(0, 10)); // "JavaScript" console.log(text.slice(0, 10)); // "JavaScript" console.log(text.slice(-8)); // "awesome!" // Replace methods console.log(text.replace("awesome", "amazing")); // "JavaScript is amazing!" // Split method let words = text.split(" "); console.log(words); // ["JavaScript", "is", "awesome!"] // Trim whitespace let messy = " Hello World "; console.log(messy.trim()); // "Hello World"
String Concatenation
javascriptlet firstName = "John"; let lastName = "Doe"; // Method 1: + operator let fullName1 = firstName + " " + lastName; // Method 2: Template literals (recommended) let fullName2 = `${firstName} ${lastName}`; // Method 3: concat() method let fullName3 = firstName.concat(" ", lastName); // Complex template literals let user = { name: "Alice", age: 30, city: "New York" }; let userInfo = ` User Information: Name: ${user.name} Age: ${user.age} City: ${user.city} Status: ${user.age >= 18 ? "Adult" : "Minor"} `;
3. Boolean
Booleans represent logical values - either true
or false
:
javascript// Direct boolean values let isActive = true; let isComplete = false; let hasPermission = true; // Boolean from comparisons let age = 25; let isAdult = age >= 18; // true let isTeenager = age < 20; // false let canVote = age >= 18; // true // Boolean from functions let userName = "john_doe"; let hasValidName = userName.length > 0; // true console.log(typeof isActive); // "boolean"
Truthy and Falsy Values
JavaScript converts values to booleans in certain contexts. Understanding truthy and falsy values is crucial:
javascript// Falsy values (convert to false) console.log(Boolean(false)); // false console.log(Boolean(0)); // false console.log(Boolean(-0)); // false console.log(Boolean(0n)); // false (BigInt zero) console.log(Boolean("")); // false (empty string) console.log(Boolean(null)); // false console.log(Boolean(undefined)); // false console.log(Boolean(NaN)); // false // Truthy values (everything else converts to true) 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 (non-empty string) console.log(Boolean([])); // true (empty array) console.log(Boolean({})); // true (empty object) // Practical usage let userInput = ""; if (userInput) { console.log("User provided input"); } else { console.log("No input provided"); // This will run }
4. Undefined
undefined
represents a variable that has been declared but not assigned a value:
javascript// Variable declared but not initialized let userName; console.log(userName); // undefined console.log(typeof userName); // "undefined" // Function with no return value function greet() { console.log("Hello!"); // No return statement } let result = greet(); // Prints "Hello!" console.log(result); // undefined // Object property that doesn't exist let user = { name: "John" }; console.log(user.age); // undefined // Array element that doesn't exist let numbers = [1, 2, 3]; console.log(numbers[10]); // undefined
5. Null
null
represents an intentional absence of value:
javascript// Intentionally empty value let data = null; let selectedItem = null; let currentUser = null; console.log(typeof null); // "object" (JavaScript quirk!) // Common usage patterns function findUser(id) { // If user not found, return null if (id === 999) { return null; } return { id: id, name: "User " + id }; } let user = findUser(999); if (user === null) { console.log("User not found"); } // Difference between null and undefined let undefinedVar; let nullVar = null; console.log(undefinedVar == null); // true (loose equality) console.log(undefinedVar === null); // false (strict equality) console.log(nullVar == undefined); // true (loose equality) console.log(nullVar === undefined); // false (strict equality)
6. Symbol (ES6+)
Symbols are unique identifiers, primarily used for object properties:
javascript// Creating symbols let sym1 = Symbol(); let sym2 = Symbol("description"); let sym3 = Symbol("description"); console.log(sym2 === sym3); // false (each symbol is unique) console.log(typeof sym1); // "symbol" // Using symbols as object keys let user = { name: "John", [Symbol("id")]: 123 }; // Symbols are not enumerable console.log(Object.keys(user)); // ["name"] (symbol key not included)
7. BigInt (ES2020+)
BigInt represents integers larger than Number.MAX_SAFE_INTEGER
:
javascript// Creating BigInt let bigNumber1 = 123n; // 'n' suffix let bigNumber2 = BigInt(123); let bigNumber3 = BigInt("123456789012345678901234567890"); console.log(typeof bigNumber1); // "bigint" // BigInt operations let a = 123n; let b = 456n; console.log(a + b); // 579n console.log(a * b); // 56088n // Cannot mix BigInt with regular numbers // console.log(123n + 456); // TypeError console.log(123n + BigInt(456)); // 579n
Non-Primitive Data Types
1. Objects
Objects are collections of key-value pairs:
javascript// Object literal syntax let person = { firstName: "John", lastName: "Doe", age: 30, isEmployed: true, address: { street: "123 Main St", city: "New York", zipCode: "10001" }, hobbies: ["reading", "swimming", "coding"] }; // Accessing properties console.log(person.firstName); // "John" console.log(person["lastName"]); // "Doe" console.log(person.address.city); // "New York" // Adding/modifying properties person.email = "john@example.com"; person.age = 31; // Deleting properties delete person.isEmployed; console.log(typeof person); // "object"
2. Arrays
Arrays are ordered lists of values:
javascript// Array literal syntax let numbers = [1, 2, 3, 4, 5]; let fruits = ["apple", "banana", "orange"]; let mixed = [1, "hello", true, null, { name: "John" }]; // Accessing elements console.log(fruits[0]); // "apple" console.log(fruits[fruits.length - 1]); // "orange" (last element) // Array properties and methods console.log(fruits.length); // 3 fruits.push("grape"); // Add to end fruits.unshift("mango"); // Add to beginning let lastFruit = fruits.pop(); // Remove from end let firstFruit = fruits.shift(); // Remove from beginning console.log(typeof fruits); // "object" console.log(Array.isArray(fruits)); // true
3. Functions
Functions are reusable blocks of code:
javascript// Function declaration function greet(name) { return "Hello, " + name + "!"; } // Function expression let sayGoodbye = function(name) { return "Goodbye, " + name + "!"; }; // Arrow function let add = (a, b) => a + b; console.log(typeof greet); // "function" console.log(greet("Alice")); // "Hello, Alice!"
Type Checking and Conversion
Checking Types
javascriptlet value = "Hello"; // typeof operator console.log(typeof value); // "string" console.log(typeof 42); // "number" console.log(typeof true); // "boolean" console.log(typeof undefined); // "undefined" console.log(typeof null); // "object" (quirk!) console.log(typeof {}); // "object" console.log(typeof []); // "object" console.log(typeof function(){}); // "function" // More specific checks console.log(Array.isArray([])); // true console.log(Array.isArray({})); // false // Constructor checks console.log(value instanceof String); // false (primitive) console.log(new String(value) instanceof String); // true (object)
Type Conversion
JavaScript performs automatic type conversion (coercion) in many situations:
javascript// Automatic conversion examples console.log("5" + 3); // "53" (number to string) console.log("5" - 3); // 2 (string to number) console.log("5" * "2"); // 10 (both strings to numbers) console.log(true + 1); // 2 (boolean to number) console.log(false + 1); // 1 (boolean to number) // Explicit conversion let str = "123"; let num = Number(str); // 123 let bool = Boolean(str); // true let number = 456; let string = String(number); // "456" let boolean = Boolean(number); // true // Parsing strings to numbers console.log(parseInt("123.45")); // 123 console.log(parseFloat("123.45")); // 123.45 console.log(parseInt("123abc")); // 123 console.log(parseInt("abc123")); // NaN
Practical Examples
1. User Registration Form
javascript// User data with different types let userData = { // Strings firstName: "Alice", lastName: "Johnson", email: "alice@example.com", // Numbers age: 28, userId: 12345, // Booleans isActive: true, hasVerifiedEmail: false, isAdmin: false, // Arrays hobbies: ["reading", "hiking", "photography"], languages: ["English", "Spanish", "French"], // Objects address: { street: "456 Oak Ave", city: "San Francisco", state: "CA", zipCode: "94102" }, // Null (optional data) phoneNumber: null, profilePicture: null, // Date (object) registrationDate: new Date(), lastLoginDate: undefined }; // Type checking and validation function validateUser(user) { let errors = []; if (typeof user.firstName !== "string" || user.firstName.length === 0) { errors.push("First name is required"); } if (typeof user.age !== "number" || user.age < 13) { errors.push("Age must be a number and at least 13"); } if (typeof user.email !== "string" || !user.email.includes("@")) { errors.push("Valid email is required"); } return errors; } let validationErrors = validateUser(userData); console.log("Validation errors:", validationErrors);
2. Shopping Cart Calculator
javascript// Shopping cart with mixed data types let shoppingCart = { items: [ { id: 1, name: "Laptop", price: 999.99, quantity: 1, inStock: true }, { id: 2, name: "Mouse", price: 25.50, quantity: 2, inStock: true }, { id: 3, name: "Keyboard", price: 75.00, quantity: 1, inStock: false } ], // Configuration taxRate: 0.08, shippingCost: 10.00, freeShippingThreshold: 100.00, // State discountCode: null, isGuestCheckout: false }; function calculateTotal(cart) { let subtotal = 0; let availableItems = 0; // Calculate subtotal for in-stock items only for (let item of cart.items) { if (item.inStock) { subtotal += item.price * item.quantity; availableItems += item.quantity; } } // Calculate tax let tax = subtotal * cart.taxRate; // Calculate shipping let shipping = subtotal >= cart.freeShippingThreshold ? 0 : cart.shippingCost; // Calculate total let total = subtotal + tax + shipping; return { subtotal: Number(subtotal.toFixed(2)), tax: Number(tax.toFixed(2)), shipping: Number(shipping.toFixed(2)), total: Number(total.toFixed(2)), itemCount: availableItems, hasUnavailableItems: cart.items.some(item => !item.inStock) }; } let orderSummary = calculateTotal(shoppingCart); console.log("Order Summary:", orderSummary);
Common Mistakes and Best Practices
1. Type Coercion Pitfalls
javascript// Unexpected results console.log(0 == false); // true (avoid ==) console.log("" == false); // true (avoid ==) console.log(null == undefined); // true (avoid ==) // Use strict equality console.log(0 === false); // false (better) console.log("" === false); // false (better) console.log(null === undefined); // false (better) // Be careful with + operator console.log("5" + 3); // "53" (concatenation) console.log(+"5" + 3); // 8 (unary + converts to number)
2. Checking for null/undefined
javascriptlet value = null; // Poor approach if (value == null) { // This catches both null and undefined } // Better approach if (value === null) { // Only catches null } if (value === undefined) { // Only catches undefined } // Check for both null and undefined if (value == null) { // Acceptable when you want to catch both } // Modern approach (nullish coalescing) let defaultValue = value ?? "default";
3. Array vs Object Detection
javascriptlet arr = []; let obj = {}; // Wrong way console.log(typeof arr); // "object" (not helpful) console.log(typeof obj); // "object" (not helpful) // Right way console.log(Array.isArray(arr)); // true console.log(Array.isArray(obj)); // false // Alternative for objects console.log(obj.constructor === Object); // true console.log(arr.constructor === Array); // true
Practice Exercises
javascript// Exercise 1: Type identification function identifyType(value) { if (Array.isArray(value)) { return "array"; } else if (value === null) { return "null"; } else { return typeof value; } } // Test the function console.log(identifyType(42)); // "number" console.log(identifyType("hello")); // "string" console.log(identifyType([])); // "array" console.log(identifyType(null)); // "null" // Exercise 2: Data validation function validateProduct(product) { let isValid = true; let errors = []; // Check required string fields if (typeof product.name !== "string" || product.name.trim() === "") { errors.push("Product name is required"); isValid = false; } // Check price is a positive number if (typeof product.price !== "number" || product.price <= 0) { errors.push("Price must be a positive number"); isValid = false; } // Check quantity is a non-negative integer if (!Number.isInteger(product.quantity) || product.quantity < 0) { errors.push("Quantity must be a non-negative integer"); isValid = false; } // Check boolean fields if (typeof product.inStock !== "boolean") { errors.push("inStock must be a boolean"); isValid = false; } return { isValid, errors }; } // Test the validation let product1 = { name: "Laptop", price: 999.99, quantity: 5, inStock: true }; let product2 = { name: "", price: -100, quantity: 2.5, inStock: "yes" }; console.log(validateProduct(product1)); // { isValid: true, errors: [] } console.log(validateProduct(product2)); // { isValid: false, errors: [...] } // Exercise 3: Type conversion utility function convertToType(value, targetType) { switch (targetType.toLowerCase()) { case "string": return String(value); case "number": let num = Number(value); return isNaN(num) ? 0 : num; case "boolean": return Boolean(value); case "array": return Array.isArray(value) ? value : [value]; default: return value; } } // Test conversions console.log(convertToType(123, "string")); // "123" console.log(convertToType("456", "number")); // 456 console.log(convertToType("hello", "boolean")); // true console.log(convertToType("world", "array")); // ["world"]
What's Next?
Excellent! You now have a solid understanding of JavaScript data types. In the next lesson, we'll explore Type Conversion in detail and learn how JavaScript handles automatic type conversion and how to perform explicit conversions safely.
Key Takeaways
- •JavaScript has 7 primitive types and 1 non-primitive (object) type
- •Use
typeof
operator to check types, but be aware of its quirks - •Understand truthy/falsy values for conditional logic
- •Use strict equality (
===
) to avoid type coercion issues - •Arrays and functions are special types of objects
- •
null
andundefined
are different - use them appropriately - •Modern features like BigInt and Symbol have specific use cases
Understanding data types is crucial for writing robust JavaScript code. They form the foundation for all data manipulation and logic in your programs!