Primitives VS non-primitives data types in JavaScript 💻

Muhammad Akram
2 min readMay 1, 2023

--

Before differentiating, first let’s understand what are data types itself? 👇

Data Types?

In programming, a data type is a classification of data based on the type of value assigned to a variable(memory placeholder in RAM).

Following are the data types specific to JavaScript but also common in most of the programming languages.

// Number
let num = 10;

// String
let str = "Hello, world!";

// Boolean
let bool = true;

// Undefined
let undef;

// Null
let n = null;

// Symbol
let sym = Symbol();

// Object
let obj = {
name: "John",
age: 30,
hobbies: ["reading", "coding"]
};

// Array
let arr = [1, 2, 3, 4, 5];

// Function
function add(x, y) {
return x + y;
}

Primitive Data Types

There are 6 primitives data types number, string, boolean, undefined, null and symbol.

Primitive data types are immutable(can not modify or change the actual value). We can also refer them as pass by value.

let originalVariable = 'Hello, Reader!'; // memory address 0x7fff02
// if we modify the originalVariable
originalVariable = originalVariable + " keep reading."
/*
now its new value is "Hello, Reader! keep reading."
modification creates a new string and assigned back with
new memory address as 0x7fff06.
*/

Non-Primitive Data Types

Non-primitives are mutable(if we make a copy of original value, modifying copy will affect the original value, because they both refer the same memory address in RAM). We can also refer them as pass by reference.

let originalVariable = [1,2,3]; // memory address 0x7fff02
let copiedVariable = originalVariable; // reference to 0x7fff02

// modifying the value of copiedVariable
copiedVariable.push(4) // [1,2,3,4]
/*
will modify the value of originalVariable also, now originalVariable
value is also [1,2,3,4]
*/
copiedVariable = [4,5,6] // Overriding or re-assigning value
/*
Overriding the value of copy, will not affect the original, because it
does not refer to the memory of originalVariable then.
*/

⚠️ There’s a difference between modifying and overriding. Overriding means assigning a new value with new memory address, where as modification means changing the actual value.

👋
Let me know in comments, if any query, correction or love ❤️

--

--