Understanding the Difference: Primitive vs Non-Primitive Data Types in JavaScript
Primitive - (String, Symbol (contain unique prop to avoid name clashes), Number, null, undefined, Boolean, BigInt) (SNNUB acronym) – Primitive is immutable (means you cannot modify anything in existing values, you can only replace it) data type.
They are passByValue, meaning modifications to a copy do not affect the original value. When comparing a == b
, it returns true if the values are equal. Primitive values are stored in the stack because they are fixed in size and faster to access.
PS: typeof null returns is Object
Non Primitive – Object, Array, functions called as non-primitive type. – Non-primitive is mutable (means you can modify existing values) data type. It is passByReference so modifying a copied value also modifies the original array/object. Non-primitive values are stored in the heap because they can be dynamic in size and require more complex memory management.
let obj = { name: "Alice" };
let copy = obj;
copy.name = "Bob";
console.log(obj.name); // Outputs: Bob