DEV Community

Fahimkhan9
Fahimkhan9

Posted on

Javascript Data Types- IN DEPTH!! -With AutoBoxing Concept,Reference Behavior.

In JavaScript, there are two types of data types.

  1. Primitive Data Type
  2. Non-Primitive Data Type.

Primitive Data Type

What is a Primitive Data Type?

Primitives are basic data types that are not objects and have no methods. Primitives are immutable (can't be changed), meaning their values cannot be changed once created. We will get to details after a while — let's get to know what primitive data types are.

String

  1. String
const name = "Alice";
Enter fullscreen mode Exit fullscreen mode
  1. Number
const age = 25;
Enter fullscreen mode Exit fullscreen mode
  1. BigInt
const big = 1234567890123456789012345678901234567890n;
Enter fullscreen mode Exit fullscreen mode
  1. Boolean
const isActive = true;
Enter fullscreen mode Exit fullscreen mode
  1. Undefined
let x;
console.log(x); // undefined
Enter fullscreen mode Exit fullscreen mode
  1. Null
const empty = null;
Enter fullscreen mode Exit fullscreen mode
  1. Symbol
const sym = Symbol("id");
Enter fullscreen mode Exit fullscreen mode

You might have one question in mind.

If string is a primitive data type, it means it doesn't have any methods and it's immutable.

But we know strings have methods like toUpperCase(), etc.? Well, you are right. Let's understand in detail.

When we use a method on any primitive (like string), JavaScript automatically wraps it in its corresponding object type so that we can access object-like methods.

Example:

const str = "hello";
const upperStr = str.toUpperCase();
console.log(upperStr); // "HELLO"
Enter fullscreen mode Exit fullscreen mode

What JavaScript does internally (conceptually):

// Step 1: You have a primitive string
let str = "hello"; // primitive string

// Step 2: JavaScript wraps it in a String object (temporary)
let tempStrObject = new String(str); // [object String]

// Step 3: Call the method on that object
let result = tempStrObject.toUpperCase(); // "HELLO"

// Step 4: Discard the object, return result
Enter fullscreen mode Exit fullscreen mode

Important: str is still "hello". The original primitive is unchanged because it's immutable.

Non-Primitive Data Type

Non-primitives are the opposite of primitives. Non-primitives are types that are not primitive.

Important: They are stored by reference, not by value.

Let's understand by an example

Primitive (stored by value)

let a = 10;
let b = a;  // b gets a copy of the value of a (10)

b = 20;

console.log(a); // 10 — ❗ a is unaffected
Enter fullscreen mode Exit fullscreen mode

Non-primitive (stored by reference)

let obj1 = { name: "Alice" };
let obj2 = obj1;  // obj2 references the same object in memory

obj2.name = "Bob";

console.log(obj1.name); // "Bob" — ❗ obj1 is affected
Enter fullscreen mode Exit fullscreen mode

Both obj1 and obj2 point to the same object in memory, so changing it through one affects the other.

Top comments (0)