Junior
What is the difference between different data types?
sobes.tech AI
Answer from AI
In JavaScript, data is divided into primitive types and objects.
Primitive types:
- String: A sequence of characters. Immutable.
- Number: Numbers, including integers and floating-point, as well as
Infinity,-Infinity, andNaN. - Boolean: Logical value (
trueorfalse). - Null: A special value representing the absence of an object.
- Undefined: The value of a variable that has not been assigned a value.
- Symbol: A unique and immutable primitive type used for object property identifiers.
- BigInt: Integers of arbitrary length.
Objects:
- Object: A collection of key-value pairs. Mutable. Examples include arrays, functions, regular expressions, dates.
Main differences:
- Mutability: Primitive types are immutable, meaning their value cannot be changed directly. Attempting to change them creates a new copy. Objects are mutable; their properties can be added, removed, and modified.
- Pass by value/reference: Primitive types are passed by value (the value itself is copied). Objects are passed by reference (a reference to the memory location where the object is stored is copied).
- Comparison: Primitive types are compared by value. Objects are compared by reference (two variables refer to the same object in memory).
// Examples
let str1 = "hello";
let str2 = str1; // str2 gets a copy of the value of str1
str1 = "world"; // A new string "world" is created for str1
console.log(str2); // "hello" - str2 did not change
let obj1 = { name: "Alice" };
let obj2 = obj1; // obj2 gets a reference to the same object as obj1
obj1.name = "Bob"; // The property of the object they both reference is changed
console.log(obj2.name); // "Bob" - obj2 reflects the change
let num1 = 10;
let num2 = 10;
console.log(num1 === num2); // true - values are compared
let objA = { value: 1 };
let objB = { value: 1 };
console.log(objA === objB); // false - references are compared (different objects, even if contents are the same)
Differences table:
| Attribute | Primitive types | Objects |
|---|---|---|
| Mutability | Immutable | Mutable |
| Passing | By value | By reference |
| Comparison | By value | By reference |
| Storage | Directly in variable | Reference to memory location |
| Data types | String, Number, Boolean, Null, Undefined, Symbol, BigInt | Object (including arrays, functions, etc.) |