JavaScript Data Types: Primitives, Objects and typeof Explained

Every value in JavaScript has a type: "Asha" is a string, 42 is a number, true is a boolean. The type decides what you can do with a value and how it behaves when you copy or compare it. In this lesson you will learn all eight JavaScript data types, how to check a type with typeof (and its traps), and the difference between primitive and reference values that causes so many test-data bugs.

Advertisement

📖 What You’ll Learn: the seven primitive types (string, number, bigint, boolean, undefined, null, symbol), the object type and its kinds (arrays, functions, dates), the typeof operator and its quirks, Array.isArray, null versus undefined, immutability of primitives, and copying by value versus by reference.


🧬 What Is a Data Type?

Definition: a data type describes what kind of value something is and which operations make sense for it. JavaScript has 8 data types: seven primitive types and one object type.

TypeExampleUsed for
string"Asha", 'QA', `hi`Text
number42, 3.14, -7, NaNIntegers and decimals
bigint9007199254740993nWhole numbers larger than 253
booleantrue, falseYes/no conditions
undefinedundefinedA value that was never set
nullnullAn intentionally empty value
symbolSymbol("id")Unique keys
object{}, [], functions, datesCollections and complex data

Because JavaScript is dynamically typed, a variable has no fixed type; the value has the type.


🔤 The Primitive Types

Definition: a primitive is a simple value that is not an object and has no properties of its own. Primitives are immutable: you cannot change a primitive value, you can only replace it with another.

📄 primitives.js

const name = "Asha";               // string
const age = 29;                    // number (integers and decimals share one type)
const price = 499.99;              // number
const views = 12345678901234567890n; // bigint (note the n)
const isActive = true;             // boolean
let nickname;                      // undefined (declared, not assigned)
const middleName = null;           // null (deliberately empty)
const id = Symbol("id");           // symbol

console.log(typeof name, typeof age, typeof price);
console.log(typeof views, typeof isActive, typeof nickname);
console.log(typeof middleName, typeof id);

⌨️ Terminal

node primitives.js

🖥️ Output

string number number
bigint boolean undefined
object symbol
  • string: text in double quotes, single quotes or back-ticks. Back-ticks allow ${...} placeholders.
  • number: one type for integers and decimals, plus the special values Infinity, -Infinity and NaN (“not a number”).
  • bigint: integers of any size, written with an n suffix. Covered in the Numbers lesson.
  • symbol: every Symbol() is unique, even with the same description. Libraries use symbols for hidden property keys.

Strings look like they have methods, and they do, but calling a method never changes the original string:

📄 immutable.js

let status = "passed";
const upper = status.toUpperCase();
console.log(status, upper);   // the original is unchanged

status[0] = "P";              // ignored: strings are immutable
console.log(status);

console.log(Symbol("id") === Symbol("id")); // every symbol is unique

⌨️ Terminal

node immutable.js

🖥️ Output

passed PASSED
passed
false

🗂️ The Object Type: Objects, Arrays, Functions and More

Definition: an object is a collection of properties (key–value pairs). Everything that is not a primitive is an object, including arrays, functions, dates, maps and regular expressions.

📄 objects.js

const user = { name: "Asha", role: "tester" };   // plain object
const scores = [91, 78, 85];                     // array (an object with numeric keys)
const greet = function () { return "hi"; };      // function (a callable object)
const today = new Date(2026, 10, 23);            // Date object
const pattern = /qa/i;                           // regular expression

console.log(typeof user, typeof scores, typeof greet);
console.log(typeof today, typeof pattern);
console.log(Array.isArray(scores), Array.isArray(user));
console.log(today instanceof Date);

⌨️ Terminal

node objects.js

🖥️ Output

object object function
object object
true false
true
  • typeof returns "object" for arrays, dates and regular expressions, so it cannot tell them apart.
  • Use Array.isArray(value) to check for an array and value instanceof Date for dates.
  • Functions are objects too, but typeof reports them as "function" because that check is so useful.

Advertisement

🔍 The typeof Operator and Its Quirks

typeof value returns the type as a string. It is safe to use even on names that were never declared.

ExpressionResultNote
typeof "hi""string"
typeof 3.5"number"
typeof NaN"number"NaN is a special number value
typeof 10n"bigint"
typeof undefined"undefined"
typeof null"object"A historical bug, kept for compatibility
typeof []"object"Use Array.isArray()
typeof function(){}"function"
typeof notDeclared"undefined"No ReferenceError

A small helper that returns a more precise type name is common in test utilities:

📄 typename.js

function typeName(value) {
  if (value === null) return "null";
  if (Array.isArray(value)) return "array";
  if (value instanceof Date) return "date";
  return typeof value;
}

const samples = [
  ["\"text\"", "text"], ["7", 7], ["NaN", NaN], ["5n", 5n], ["true", true],
  ["undefined", undefined], ["null", null], ["[1]", [1]], ["{ a: 1 }", { a: 1 }],
  ["new Date()", new Date()], ["() => {}", () => {}],
];
for (const [label, value] of samples) {
  console.log(label.padEnd(12), "->", typeName(value));
}

⌨️ Terminal

node typename.js

🖥️ Output

"text"       -> string
7            -> number
NaN          -> number
5n           -> bigint
true         -> boolean
undefined    -> undefined
null         -> null
[1]          -> array
{ a: 1 }     -> object
new Date()   -> date
() => {}     -> function

💡 Tip: To check for null reliably, compare directly: value === null. Never rely on typeof value === "object" alone, because null passes that check too.


🕳️ undefined vs null

Both mean “no value”, but they are used differently:

undefinednull
MeaningNot set yet / missingDeliberately empty
Who sets itUsually JavaScript itselfUsually you (or an API)
Where you see itUnassigned variables, missing properties, functions with no return, missing argumentsAPI fields with no value, “clear this field”
typeof"undefined""object"
In JSONOmitted from the outputKept as null

📄 null-undefined.js

const order = { id: 101, coupon: null };

let shippedAt;
function log() {}

console.log(shippedAt);          // never assigned
console.log(order.trackingNo);    // property does not exist
console.log(log());              // function with no return value
console.log(order.coupon);       // explicitly empty

console.log(JSON.stringify({ a: undefined, b: null }));
console.log(null == undefined, null === undefined);

⌨️ Terminal

node null-undefined.js

🖥️ Output

undefined
undefined
undefined
null
{"b":null}
true false

The last line previews the next lessons: loose equality == treats null and undefined as equal, strict equality === does not.


Advertisement

📋 Copy by Value vs Copy by Reference

This is the most important difference between primitives and objects, and a frequent source of test bugs.

  • Primitives are copied by value. The new variable gets its own copy.
  • Objects are copied by reference. The new variable points to the same object, so a change through one name is visible through the other.

📄 reference.js

let a = 10;
let b = a;       // copy of the value
b = 20;
console.log("primitives:", a, b);

const original = { user: "asha", role: "tester" };
const copy = original;          // copy of the reference (same object)
copy.role = "admin";
console.log("objects:", original.role, copy.role);
console.log("same object?", original === copy);

⌨️ Terminal

node reference.js

🖥️ Output

primitives: 10 20
objects: admin admin
same object? true

To get an independent copy of an object, create a new one. structuredClone() makes a deep copy, including nested objects:

📄 clone.js

const baseUser = { name: "asha", address: { city: "Pune" } };

const shallow = { ...baseUser };          // new top-level object
const deep = structuredClone(baseUser);   // new object at every level

shallow.name = "ravi";
shallow.address.city = "Delhi";           // nested object is still shared!
deep.address.city = "Mumbai";

console.log(baseUser);
console.log(deep);

⌨️ Terminal

node clone.js

🖥️ Output

{ name: 'asha', address: { city: 'Delhi' } }
{ name: 'asha', address: { city: 'Mumbai' } }

⚠️ Watch out: A common flaky-test pattern: a shared test-data object is modified by one test, and the next test receives the changed data. Build fresh data for each test, or clone a template with structuredClone().

The same rule applies to comparison: two objects are equal only if they are the same object.

📄 compare.js

console.log({ id: 1 } === { id: 1 });   // two different objects
console.log([1, 2] === [1, 2]);
const x = { id: 1 };
const y = x;
console.log(x === y);                   // same reference

⌨️ Terminal

node compare.js

🖥️ Output

false
false
true

🧪 Tester Scenario: Validate the Types in an API Response

API tests often check that each field has the right type, not just the right value. This example validates a user object against a simple schema:

📄 schema-check.js

const response = {
  id: 42,
  email: "qa@sqatools.in",
  active: true,
  roles: ["tester"],
  manager: null,
  createdAt: "2026-11-23T10:00:00Z",
};

const schema = {
  id: "number",
  email: "string",
  active: "boolean",
  roles: "array",
  manager: "null",
  createdAt: "string",
};

function typeName(v) {
  if (v === null) return "null";
  if (Array.isArray(v)) return "array";
  return typeof v;
}

let errors = 0;
for (const field in schema) {
  const actual = typeName(response[field]);
  const ok = actual === schema[field];
  if (!ok) errors++;
  console.log(`${ok ? "PASS" : "FAIL"} ${field}: expected ${schema[field]}, got ${actual}`);
}
console.log(errors === 0 ? "Schema check passed" : `${errors} field(s) failed`);

⌨️ Terminal

node schema-check.js

🖥️ Output

PASS id: expected number, got number
PASS email: expected string, got string
PASS active: expected boolean, got boolean
PASS roles: expected array, got array
PASS manager: expected null, got null
PASS createdAt: expected string, got string
Schema check passed

Real projects use schema libraries (Ajv for JSON Schema, Zod) for this, but they rely on exactly these type checks.


Advertisement

📝 Practice Questions with Answers

Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.

Q1. Print the typeof result for "42", 42, 42n, [42] and { n: 42 }.

Show answer

📄 practice1.js

console.log(typeof "42");
console.log(typeof 42);
console.log(typeof 42n);
console.log(typeof [42]);
console.log(typeof { n: 42 });

🖥️ Output

string
number
bigint
object
object

Q2. Write a function isPlainObject(value) that returns true only for objects like {}, and false for null, arrays and primitives.

Show answer

📄 practice2.js

function isPlainObject(value) {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}

console.log(isPlainObject({ a: 1 }));
console.log(isPlainObject(null));
console.log(isPlainObject([1, 2]));
console.log(isPlainObject("text"));

🖥️ Output

true
false
false
false

Q3. Predict the output, then run it.

const cart = { items: 2 };
const saved = cart;
saved.items = 5;
let count = cart.items;
count = 10;
console.log(cart.items, saved.items, count);
Show answer

📄 practice3.js

const cart = { items: 2 };
const saved = cart;
saved.items = 5;
let count = cart.items;
count = 10;
console.log(cart.items, saved.items, count);

🖥️ Output

5 5 10

saved and cart are the same object, so both show 5. count received a copy of the number 5, so changing it to 10 does not affect the object.

Q4. Create a test-data template { name: "asha", tags: ["ui"] }. Make an independent copy, add "api" to the copy’s tags, and show that the template did not change.

Show answer

📄 practice4.js

const template = { name: "asha", tags: ["ui"] };
const user = structuredClone(template);
user.tags.push("api");

console.log("template:", template.tags);
console.log("copy:", user.tags);

🖥️ Output

template: [ 'ui' ]
copy: [ 'ui', 'api' ]

A spread copy { ...template } would share the same tags array, so the template would change too.

Q5. Which of these values are primitives: "abc", null, [], Symbol(), new Date(), 0n, function(){}?

Show answer

Primitives: "abc", null, Symbol(), 0n. Objects: [], new Date(), function(){}.

Q6. An API returns { discount: null } for one product and {} for another. Write code that prints no discount field, discount is empty or the discount value for each case.

Show answer

📄 practice6.js

function describe(product) {
  if (product.discount === undefined) return "no discount field";
  if (product.discount === null) return "discount is empty";
  return `discount ${product.discount}%`;
}

console.log(describe({ discount: null }));
console.log(describe({}));
console.log(describe({ discount: 15 }));

🖥️ Output

discount is empty
no discount field
discount 15%

🧠 MCQ Quiz: Data Types

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. How many data types does JavaScript have?
  2. What is typeof null?
  3. What is typeof [1, 2, 3]?
  4. What is typeof NaN?
  5. Which value is not a primitive?
  6. After const a = { n: 1 }; const b = a; b.n = 2;, what is a.n?
  7. What does { id: 1 } === { id: 1 } return?
  8. What does JSON.stringify({ a: undefined, b: null }) return?
  9. Which creates an independent deep copy of an object?
  10. What is the result of Symbol("id") === Symbol("id")?

💼 Interview Questions and Answers

Q1. List the JavaScript data types and say which are primitives.

There are eight: string, number, bigint, boolean, undefined, null and symbol are primitives; object covers everything else, including arrays, functions, dates, maps, sets and regular expressions. Primitives are immutable and compared by value; objects are mutable and compared by reference.

Q2. What is the difference between null and undefined?

undefined means a value was never assigned: unassigned variables, missing properties, missing arguments and functions without return. null is an explicit “no value” that a developer or API sets on purpose. typeof undefined is "undefined" while typeof null is "object"; null == undefined is true but null === undefined is false; JSON keeps null but drops undefined properties.

Q3. How do you reliably check whether a value is an array, an object or null?

📄 check.js

const check = (v) =>
  v === null ? "null"
  : Array.isArray(v) ? "array"
  : typeof v === "object" ? "object"
  : typeof v;

console.log(check(null), check([]), check({}), check(5));

⌨️ Terminal

node check.js

🖥️ Output

null array object number

For more precise names, Object.prototype.toString.call(v) returns strings such as "[object Date]".

Q4. Explain pass-by-value and pass-by-reference in JavaScript.

JavaScript always passes arguments by value, but for objects the value is a reference. So a function that changes a property of an object argument changes the caller’s object, while reassigning the parameter to a new object does not affect the caller. Primitives are copied, so changes inside the function never leak out.

📄 pass.js

function update(user, count) {
  user.name = "changed";   // visible to the caller
  user = { name: "new" };  // only changes the local parameter
  count = 99;              // only changes the local copy
}

const u = { name: "asha" };
let c = 1;
update(u, c);
console.log(u.name, c);

⌨️ Terminal

node pass.js

🖥️ Output

changed 1

Q5. What is the difference between a shallow and a deep copy?

A shallow copy ({ ...obj }, Object.assign({}, obj), [...arr]) creates a new top-level container but nested objects are still shared. A deep copy (structuredClone(obj)) duplicates every level. JSON.parse(JSON.stringify(obj)) is an older deep-copy trick that loses undefined, functions, dates (they become strings), Map and Set.


Advertisement

❓ Frequently Asked Questions

🤔 Is an array a data type in JavaScript?

Not a separate one. Arrays are a kind of object, which is why typeof [] is "object". Use Array.isArray() to detect them.

🤔 Why is typeof null “object”?

In the first implementation of JavaScript, values were stored with a type tag, and the tag for objects was 0. null was represented as a null pointer, also 0, so it was reported as an object. Fixing it would break existing websites.

🤔 Does JavaScript have an integer type?

Regular numbers are all 64-bit floating point, used for both integers and decimals. For integers larger than 253 − 1, use bigint.

🤔 When should I use null instead of undefined?

Use null when you deliberately set “no value”, for example to clear a field or to send an empty value in JSON. Let undefined mean “not set”.


🏁 Summary

  • JavaScript has 8 data types: 7 primitives (string, number, bigint, boolean, undefined, null, symbol) and object.
  • typeof returns the type name, but reports null and arrays as "object"; use === null and Array.isArray().
  • undefined means “not set”; null means “deliberately empty”.
  • Primitives are immutable and copied by value; objects are mutable and copied and compared by reference.
  • Use structuredClone() for independent deep copies of test data.

Next, continue with Lesson 8: Type Conversion and Coercion. For extra practice, solve the JavaScript data types practice programs.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in