Junior
Milline on erinevate andmetüüpide vahe?
sobes.tech AI
Vastus AI-lt
In JavaScript, data is divided into primitive types and objects.
Primitive types:
- String: Sequence of characters. Immutable.
- Number: Numbers, including integers and floating-point, as well as
Infinity,-Infinity, andNaN. - Boolean: Logical value (
trueorfalse). - Null: 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 as identifiers for object properties.
- BigInt: Integers of arbitrary length.
Objects:
- Object: A collection of key-value pairs. Mutable. Examples: arrays, functions, regular expressions, dates.
Main differences:
- Mutability: Primitive types are immutable, meaning their values cannot be changed directly. Attempting to change creates a new copy. Objects are mutable, and their properties can be added, removed, or changed.
- Pass by value/reference: Primitive types are passed by value (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 str1's value
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 references the same object as obj1
obj1.name = "Bob"; // The object's property is changed, both variables point to it
console.log(obj2.name); // "Bob" - obj2 has changed
let num1 = 10;
let num2 = 10;
console.log(num1 === num2); // true - values are equal
let objA = { value: 1 };
let objB = { value: 1 };
console.log(objA === objB); // false - references are compared (pointing to different objects, even if contents are same)
Comparison table:
| Feature | 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 | Objects (including arrays, functions, etc.) |