Online Compiler logoOnline Compiler

JavaScript Tutorial

JavaScript Data Types: Primitives and Objects

Data types define how values behave in memory and operations. Strong type awareness prevents runtime errors and logical bugs.

Why this matters

Type confusion causes common issues like incorrect comparisons, unexpected coercion, and method errors.

Primitive Types and Their Behavior

JavaScript primitives include string, number, bigint, boolean, undefined, null, and symbol.

Primitives are immutable values. Operations create new values rather than changing original primitive data.

typeof helps with quick checks, but note that typeof null returns object due to historical behavior.

Reference Types and Mutation

Objects, arrays, and functions are reference types. Assignment copies the reference, not deep content.

Mutating through one reference affects all references pointing to same object.

Use spread or structuredClone for safer copy patterns when immutability is needed.

Code Examples

Primitive Type Checks

const user = "Asha";
const score = 91;
const active = true;
let note;
const nothing = null;

console.log(typeof user);    // string
console.log(typeof score);   // number
console.log(typeof active);  // boolean
console.log(typeof note);    // undefined
console.log(typeof nothing); // object (legacy behavior)

Use type checks before method calls for safer code.

Reference Mutation

const a = { theme: "light" };
const b = a;
b.theme = "dark";
console.log(a.theme); // dark

Both variables point to same object in memory.

Shallow Copy with Spread

const original = { name: "Ravi", city: "Pune" };
const copied = { ...original };
copied.city = "Delhi";

console.log(original.city); // Pune
console.log(copied.city);   // Delhi

Spread creates a new top-level object reference.

Common Mistakes and Fixes

Using == with mixed types

Prefer strict equality (===) to avoid coercion surprises.

Treating null and undefined as same always

Handle them intentionally based on business logic.

Assuming object assignment clones data

Use copy patterns when independent objects are required.

Frequently Asked Questions

How many primitive types exist in JavaScript?

Seven: string, number, bigint, boolean, undefined, null, and symbol.

Why does typeof null return object?

It is a long-standing language quirk kept for backward compatibility.

How can I deep copy objects safely?

Use structuredClone where available, or robust deep-copy strategies based on data structure.

Is array a primitive or object?

Array is a reference type (object).

Related JavaScript Topics