Primitive Data Types vs Non-Primitive Data Types in JavaScript

Primitive Data Types or Value Data Types

Primitive data types in JavaScript are called "value types" or "primitive types" because they are stored and passed around as actual values, rather than as references to values.


Key Characteristics of Primitive Data Types

1. Stored as Actual Values: When you assign a primitive value to a variable, the variable stores the actual value, rather than a reference to the value.

2. Passed by Value: When you pass a primitive value as an argument to a function, the function receives a copy of the original value, rather than a reference to it.

3. Immutable: Primitive values are immutable, meaning they cannot be changed after they are created.


Example

let x = 5;
let y = x; // y receives a copy of the value of x

x = 10; // change the value of x

console.log(y); // Output: 5


In this example, x and y are assigned the same primitive value, 5. When x is reassigned to 10, y remains unchanged, because it has its own copy of the original value.


Conclusion

Primitive data types in JavaScript are called "value types" or "primitive types" because they are stored and passed around as actual values, rather than as references to values. This behavior allows for efficient and predictable manipulation of simple data types.



Non-Primitive Data Types or Reference Data Types 

In JavaScript, non-primitive data types (such as objects, arrays, and functions) are also referred to as reference data types because of how they are stored and passed around in the language.


Key Characteristics of Reference Data Types

1. Stored as References: When you assign a non-primitive value to a variable, the variable stores a reference to the original value, rather than a copy of the value itself.

2. Passed by Reference: When you pass a non-primitive value as an argument to a function, the function receives a reference to the original value, rather than a copy.

3. Changes are Reflected: Since multiple variables can reference the same non-primitive value, changes made to the value through one variable can be reflected in other variables that reference the same value.


Example

let obj1 = { name: 'John' };
let obj2 = obj1; // obj2 references the same object as obj1

obj2.name = 'Jane'; // change the object through obj2

console.log(obj1.name); // Output: Jane


In this example, obj1 and obj2 reference the same object. Changes made to the object through obj2 are reflected in obj1.


Conclusion

Non-primitive data types in JavaScript are called reference data types because they are stored and passed around as references to the original values, rather than as copies of the values themselves. This behavior allows for efficient sharing and modification of complex data structures.

Comments

Popular posts from this blog

Quotation marks to wrap an element in HTML

What is the difference between iostream and iostream.h in cpp?

The Basic Structure of a Full-Stack Web App