Thuta Learning
JavaScript
BasicProgrammingBeginner

JS Data Types

JavaScriptLesson 525 min

What you'll walk away with

  • Name the seven primitive types (string, number, bigint, boolean, undefined, null, symbol) plus object, with an example of each
  • Predict what typeof returns and use the right checks for null and arrays
  • Explain the difference between undefined and null
  • Convert strings with Number() and detect NaN with Number.isNaN()

Explain it simply

Explain it simply

A data type is the kind of a value: text, a number, true or false, or nothing at all. The kind decides what you can do with the value. You can add two numbers, and you can turn text into capital letters.

In JavaScript the value carries the type, not the variable, so one variable can hold a number now and a string later. That freedom is convenient, but it causes bugs when values that look alike, such as "5" (text) and 5 (a number), get mixed up.

Problem → Why → Solution

The problem: 2 + 1 becomes 21

On a shop page the user types 2 into the quantity box. The code adds 1 for a free extra item, and the cart shows 21 instead of 3. No error appears, and the customer could end up billed for twenty-one items.

cart.js
// values read from a form field are always strings
const quantity = "2";
const extra = 1;

console.log(quantity + extra);  // "21", not 3
console.log(typeof quantity);   // "string" - the clue

Why 21?

When either side of + is a string, + joins text instead of adding. Values from HTML inputs, URLs and prompt() are strings even when they look like numbers. JavaScript never warns you about the mismatch, so you have to know to check a value's type with typeof and convert it with Number() before doing math.

Core concept: seven primitives and objects

JavaScript is dynamically typed: types belong to values, not to variables. Values fall into two groups. Primitives are simple values that cannot be changed and are compared by value. Everything else (plain objects, arrays, functions, dates) is an object, stored by reference, so two objects with the same content are not ===. You can watch the dynamic part directly: let value = 5; value = "five"; is perfectly legal, and typeof value changes from "number" to "string". Count the primitives carefully: with bigint there are seven (string, number, bigint, boolean, undefined, null, symbol).

TypeExampleNote
string"Hello", 'Hi', `Hey`Text
number100, 3.14, -7, NaNIntegers and decimals alike
bigint9007199254740993nWhole numbers of any size
booleantrue, falseYes/no values
undefinedlet car;No value assigned yet
nulllet middleName = null;Deliberately empty
symbolSymbol("id")A unique key
object{ name: "Mya" }, [1, 2]Everything that is not primitive

The typeof operator returns a value's type as a string such as "number" or "string". Remember two quirks. typeof null returns "object": a bug from the very first version of JavaScript that was never fixed because fixing it would break old websites. Arrays also report "object", while functions report "function". So check null with x === null and arrays with Array.isArray(x).

undefined and null both mean "no value", but they differ in who says so. undefined comes from JavaScript: a variable with nothing assigned yet, a property that does not exist. null is a programmer's deliberate choice: "there is intentionally nothing here". A single number type stores both integers and decimals as 64-bit floating point, so 0.1 + 0.2 is 0.30000000000000004 and whole numbers are exact only up to Number.MAX_SAFE_INTEGER (9007199254740991); beyond that, use bigint.

Mental model: check the type before you use it
  1. Values carry types; variables do not
  2. Seven primitives, everything else object
  3. typeof returns the type as a string
  4. Convert strings before doing math

Do not trust typeof for null: test it with === null.

General pattern

javascript
typeof value              // "string", "number", "bigint", "boolean",
                          // "undefined", "symbol", "object" or "function"
value === null            // the only reliable null check
Array.isArray(value)      // the reliable array check

Number(text)              // string -> number (NaN if it is not numeric)
String(value)             // anything -> string
Boolean(value)            // anything -> true or false

typeof returns one of eight results as a string. Calling Number(), String() or Boolean() without new converts a value to that primitive type.

Example: typeof on every type

This example covers every type, including bigint, symbol and null, and each console.log prints its results on one line separated by spaces. Predict the last two lines before you run it.

types.js
let length = 16;                    // number
let color = "Yellow";               // string
let isDone = true;                  // boolean
let car;                            // undefined: declared, no value yet
let middleName = null;              // null: deliberately empty
let population = 9007199254740993n; // bigint: whole numbers of any size
let id = Symbol("id");              // symbol: a unique key
let person = { firstName: "John", lastName: "Doe" }; // object

console.log(typeof length, typeof color, typeof isDone);
console.log(typeof car, typeof population, typeof id);
console.log(typeof person, typeof [1, 2]);
console.log(typeof middleName, middleName === null);

Code breakdown

  1. Line 4let car;

    Declared without a value, so JavaScript sets car to undefined automatically.

  2. Line 6let population = 9007199254740993n;

    The trailing n makes it a bigint. Without the n, this number is past the safe-integer limit and would be rounded to 9007199254740992.

  3. Line 12console.log(typeof person, typeof [1, 2]);

    The object and the array both report "object", which shows that typeof alone cannot tell an array apart.

  4. Line 13console.log(typeof middleName, middleName === null);

    Shows the typeof null quirk ("object") next to the check that really works: === null returns true.

You should see
number string boolean
undefined bigint symbol
object object
object true

Type conversion: from string to number

+ joins text when it meets a string, but *, - and / quietly convert strings to numbers. Instead of relying on this automatic conversion (coercion), convert with Number() yourself, and then use Number.isNaN() to catch the NaN produced by input that is not numeric.

convert.js
const fromInput = "5";
console.log(fromInput + 1);               // 51: + joins strings
console.log(fromInput * 2);               // 10: * converts to a number
console.log(Number(fromInput) + 1);       // 6: convert first, then add
console.log(Number("abc"));               // NaN: not a number
console.log(Number.isNaN(Number("abc"))); // true
console.log(0.1 + 0.2);                   // 0.30000000000000004

Oddly but truly, typeof NaN is "number" and NaN === NaN is false, which is why you cannot test for it with === NaN and must use Number.isNaN(). Number() is also strict about the whole string: Number("12px") is NaN, while parseInt("12px", 10) reads the leading digits and returns 12. Watch out for empty input too, because Number("") is 0, not NaN.

In real projects

Where this shows up in real projects

JSON data from APIs contains only strings, numbers, booleans, null, arrays and objects; JSON knows nothing about undefined, bigint or symbol. APIs usually say "this field has no value" with null, so checks like user.phone === null appear everywhere. Large IDs are often sent as strings precisely because of the number type's safe-integer limit.

Money apps avoid the 0.1 + 0.2 problem by storing prices as whole cents, 1999 instead of 19.99 dollars, and converting only for display. Every value that comes from a form is converted with Number() and checked for NaN before it is sent to the server. Runtime validation libraries such as Zod exist largely to answer one question at that boundary: is this value really the type the rest of the code expects?

Common mistakes

Common mistakes

1. Testing for null with typeof

if (typeof data === "object") is also true when data is null, and reading data.name on the next line throws TypeError: Cannot read properties of null. Check data !== null first.

2. Doing math directly on input strings

Adding two form fields as a + b gives "10" + "5" = "105". Convert first with Number(a) + Number(b), and catch invalid input with Number.isNaN().

3. Comparing decimals with ===

0.1 + 0.2 === 0.3 is false. For money, calculate in whole units such as cents, or round with toFixed(2) when you display the result.

4. Detecting arrays with typeof

typeof [] is "object", not "array", so typeof x === "array" is never true. Use Array.isArray(x).

Best practices

Best practices

  • Convert and check types where data enters the program (forms, URLs, APIs), so the rest of the code only sees values of the right type.
  • Use null, not undefined, when you yourself want to say "nothing here".
  • Keep each variable to one type; a value that is a number now and a string later is hard to follow.

Mini challenge

Mini challenge: inspecting form data

Inspect the types of values that arrive from a form, show the string-math bug, then convert to numbers and calculate correctly.

  • Print typeof rawAge and typeof rawQuantity on one line
  • Show the wrong result of rawAge + 1 labelled "String math:"
  • Convert with Number(), then print the new types and "Number math:"
  • Print "Total items:" (quantity * 2) and "Has coupon:" using coupon !== null
form-data.js
const rawAge = "25";      // values from a form arrive as strings
const rawQuantity = "3";
const coupon = null;      // the user left the coupon field empty

// TODO: print the types of rawAge and rawQuantity on one line
// TODO: print "String math:" followed by rawAge + 1

// TODO: convert both raw values to numbers
// TODO: print their types again, then "Number math:" with age + 1
// TODO: print "Total items:" (quantity * 2) and "Has coupon:" (true/false)

Expected: Six lines are printed: string string String math: 251 number number Number math: 26 Total items: 6 Has coupon: false

Show hint

Two arguments, as in console.log("Has coupon:", coupon !== null), print with a space between them. Do not use typeof coupon; it would only say "object".

Show solution
form-data.js
const rawAge = "25";
const rawQuantity = "3";
const coupon = null;

console.log(typeof rawAge, typeof rawQuantity);
console.log("String math:", rawAge + 1);

const age = Number(rawAge);
const quantity = Number(rawQuantity);
console.log(typeof age, typeof quantity);
console.log("Number math:", age + 1);
console.log("Total items:", quantity * 2);
console.log("Has coupon:", coupon !== null);

Quick quiz 1 / 3

What does console.log(typeof null); print?

Quick quiz 2 / 3

What does console.log("10" + 2, "10" * 2); print?

Quick quiz 3 / 3

How do you reliably check whether a value is an array?

What to remember

  • There are seven primitives (string, number, bigint, boolean, undefined, null, symbol); everything else is an object.
  • typeof returns the type as a string but says "object" for null and arrays, so use === null and Array.isArray().
  • undefined means nothing was assigned yet; null means deliberately empty.
  • Form values are strings: convert them with Number() and check the result with Number.isNaN().

MDN — JavaScript Guide — MDN Web Docs

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

JS Data Types | Thuta Learning