Problem Statement
List all JavaScript data types. Explain the difference between primitive and reference types.
Explanation
In JavaScript we have two main categories of data types: primitive and reference types.
The 7 primitive types are: string, number, bigint, boolean, undefined, null, and symbol.
Reference types are basically objects, which include regular objects, arrays, and functions.
Primitives are immutable and stored by value, so when you copy them you get a separate value.
Reference types are mutable and stored by reference, so when you copy them you’re copying a reference to the same object in memory.
Code Solution
SolutionRead Only
// 7 PRIMITIVE TYPES
// 1. String
let name = 'John';
let message = "Hello";
let template = `Hi ${name}`;
// 2. Number
let age = 25;
let price = 19.99;
let infinity = 1 / 0; // Infinity
let notNumber = 'text' / 2; // NaN
// 3. BigInt
let huge = 9007199254740991n;
// 4. Boolean
let isActive = true;
// 5. undefined
let notAssigned;
console.log(notAssigned); // undefined
// 6. null
let empty = null;
// 7. Symbol
let id1 = Symbol('id');
let id2 = Symbol('id');
console.log(id1 === id2); // false (always unique)
// REFERENCE TYPES
let person = { name: 'John', age: 30 };
let numbers = [1, 2, 3];
function greet() { }
// PRIMITIVE vs REFERENCE BEHAVIOR
// Primitives - copy by value
let a = 5;
let b = a; // Copy of value
b = 10;
console.log(a); // 5 (unchanged)
console.log(b); // 10
// Reference - copy by reference
let obj1 = { value: 5 };
let obj2 = obj1; // Reference to same object
obj2.value = 10;
console.log(obj1.value); // 10 (changed!)
console.log(obj2.value); // 10
// Primitive comparison
let str1 = 'hello';
let str2 = 'hello';
console.log(str1 === str2); // true (same value)
// Reference comparison
let arr1 = [1, 2, 3];
let arr2 = [1, 2, 3];
console.log(arr1 === arr2); // false (different objects)
// Primitive immutability
let text = 'hello';
text[0] = 'H'; // Ignored
console.log(text); // 'hello' (unchanged)
// Reference mutability
let list = [1, 2, 3];
list[0] = 10; // Changes the array
list.push(4); // Adds to array
console.log(list); // [10, 2, 3, 4]