What are the data types in JavaScript?
JavaScript has 8 data types. Seven are primitives: string, number, bigint, boolean, undefined, null and symbol. The eighth is object, which covers arrays, functions, dates, maps and everything else. Primitives are immutable and copied by value. Objects are copied by reference.
Full answerHide full answer2 min read
Primitive vs reference
- A primitive variable holds the value itself, so copying it gives you an independent copy.
- An object variable holds a reference (an address) to the object in memory. Copying the variable copies the address, so both variables point to the same object.
// Primitives: copied by value
let a = 10;
let b = a;
b = 20;
console.log(a); // 10 — a is untouched
// Objects: copied by reference
const user1 = { name: "Asha" };
const user2 = user1;
user2.name = "Ravi";
console.log(user1.name); // "Ravi" — both variables point to the same objectWhat typeof returns
| Value | typeof result |
|---|---|
"hello" | "string" |
42, 3.14, NaN | "number" |
10n | "bigint" |
true | "boolean" |
undefined | "undefined" |
Symbol("id") | "symbol" |
null | "object", a bug from JavaScript's first version that was kept for backward compatibility |
{}, [], new Date() | "object" |
function () {} | "function" (functions are objects, but typeof reports them separately) |
Follow-ups
- How do you check if a value is an array? Use
Array.isArray(value), becausetypeof []gives"object". - Is JavaScript statically or dynamically typed? Dynamically typed. A variable's type is decided at runtime and can change, so
let x = 5; x = "five";is valid. TypeScript adds static types on top. - Is JavaScript pass-by-reference? No, it's always pass-by-value. For objects, though, the value being passed is a reference. A function can change the object you pass in, but reassigning the parameter doesn't affect the caller:
function update(obj) {
obj.count = 1; // mutates the shared object → the caller sees it
obj = { count: 99 }; // only rebinds the local parameter → the caller doesn't
}
const data = { count: 0 };
update(data);
console.log(data.count); // 1