JavaScriptBeginner

JavaScript Data Types: String, Number, Boolean and More

Learn the JavaScript data types: string, number, boolean, null, undefined and BigInt, and use typeof to check the type of any value.

All JavaScript lessons

What you will learn

Every value in JavaScript has a type. The text "Hello", the number 42 and the answer true are all different kinds of data, and JavaScript treats each kind differently. In this lesson you will meet the basic data types: string, number, boolean, null, undefined and BigInt, and learn how to check any value with typeof.

What is a data type?

A data type tells JavaScript what kind of value it is dealing with, and therefore what you can do with it.

Think of a kitchen. You have a jar for sugar, a bottle for water, and a switch for the light. Each holds something different and you use each one differently. You can add two numbers, but adding two switches makes no sense. Types help JavaScript know what makes sense.

JavaScript has primitive types (simple, single values) and objects (collections of values). This lesson covers the primitives. Objects and arrays get their own lessons later.

The main primitive types are:

Type Example What it stores
string "Hello" Text
number 42, 3.14 Whole and decimal numbers
boolean true, false Yes or no
null null “Nothing”, set on purpose
undefined undefined “No value yet”
bigint 9007199254740993n Very large whole numbers

(There is also a seventh primitive called symbol, used in advanced code. You can ignore it for now.)

Checking a type with typeof

The typeof operator tells you the type of a value:

console.log(typeof "Hello");   // "string"
console.log(typeof 42);        // "number"
console.log(typeof true);      // "boolean"

It works on variables too:

const age = 25;
console.log(typeof age);       // "number"

Keep typeof in your pocket. Whenever you are confused about a value, print its type.

String

A string is text. Put it inside single quotes, double quotes or backticks:

const firstName = "Riya";
const city = 'Mumbai';
const message = `Welcome to MyCodeNest`;

console.log(typeof firstName); // "string"

Single and double quotes behave the same. Just be consistent. Backticks are special, because they allow template literals, which you will learn in the strings lesson.

Some important points:

  • Numbers inside quotes are strings. "100" is text, not a number.
  • The length of a string is available with .length.
  • You can join strings with +.
const price = "100";
console.log(typeof price);      // "string"

const word = "JavaScript";
console.log(word.length);       // 10

console.log("Java" + "Script"); // "JavaScript"

If your text has the same quote inside it, use the other kind of quote, or put a backslash \ before it:

console.log("It's a sunny day");        // double quotes outside, apostrophe inside
console.log('She said "hello"');        // single quotes outside
console.log('It\'s a sunny day');       // escape with a backslash

Number

JavaScript has one type for all numbers: number. Whole numbers and decimals are both numbers.

const students = 30;      // integer
const price = 99.99;      // decimal
const temperature = -5;   // negative

console.log(typeof students);     // "number"
console.log(typeof price);        // "number"

You can do maths with them (the operators lesson covers this in detail):

console.log(10 + 5);   // 15
console.log(10 / 4);   // 2.5

Special number values

JavaScript has three special values that are also of type number:

console.log(1 / 0);          // Infinity
console.log(-1 / 0);         // -Infinity
console.log("hello" * 2);    // NaN

console.log(typeof NaN);     // "number"  (surprising, but true)
  • Infinity is what you get when you divide by zero.
  • NaN means Not a Number. You get it when a calculation makes no sense, such as multiplying text by 2. NaN is a tricky one, and it is not even equal to itself. We handle it in the numbers lesson.

A famous surprise

Computers store decimals in a way that is not always exact:

console.log(0.1 + 0.2);   // 0.30000000000000004

This is not a JavaScript bug. Almost every programming language does the same. When you work with money, a common trick is to calculate in whole units (paise instead of rupees) or to round the final answer.

Safe integer limit

A number can safely store whole numbers only up to about 9 quadrillion:

console.log(Number.MAX_SAFE_INTEGER);   // 9007199254740991

Beyond that, calculations lose accuracy. For that case, JavaScript has BigInt.

Boolean

A boolean has only two possible values: true and false. Booleans are the answers to yes/no questions, and they are the base of every decision a program makes.

const isLoggedIn = true;
const hasPaid = false;

console.log(typeof isLoggedIn);   // "boolean"

Booleans usually come from comparisons:

console.log(10 > 5);    // true
console.log(3 === 4);   // false

Write true and false in lowercase and without quotes. "true" in quotes is a string, not a boolean.

console.log(typeof true);     // "boolean"
console.log(typeof "true");   // "string"

undefined

undefined means “a variable exists, but no value has been given to it yet”. JavaScript puts it there automatically.

let score;
console.log(score);          // undefined
console.log(typeof score);   // "undefined"

You also get undefined when you ask for something that does not exist:

const user = { name: "Aman" };
console.log(user.age);       // undefined (no such property)

null

null also means “no value”, but with a big difference: you set it on purpose, to say “this is empty, and I know it is empty.”

let selectedSeat = null;   // nobody has chosen a seat yet
console.log(selectedSeat); // null

null vs undefined

Both look like “nothing”, so here is an easy way to remember:

  • undefined: JavaScript says “I do not have a value here yet.”
  • null: You say “I decided that there is no value here.”

Think of an empty parking spot. undefined is a spot that was never marked. null is a spot you marked with a sign saying “Empty”.

let a;              // undefined (never assigned)
let b = null;       // null (empty on purpose)

console.log(a, b);  // undefined null

The typeof null bug

There is one famous oddity in JavaScript:

console.log(typeof null);   // "object"

null is not an object. This is an old mistake from the first version of JavaScript that could never be fixed without breaking old websites. Just remember it. To check for null, compare it directly: value === null.

BigInt

When a whole number is too big for the normal number type, use BigInt. Add the letter n at the end of the number:

const big = 9007199254740993n;
console.log(big);           // 9007199254740993n
console.log(typeof big);    // "bigint"

Compare with a normal number, which loses accuracy:

console.log(9007199254740993);    // 9007199254740992  (wrong last digit!)
console.log(9007199254740993n);   // 9007199254740993n (correct)

BigInt follows two rules:

  • It holds only whole numbers. 1.5n is invalid.
  • You cannot mix it with a normal number in maths:
console.log(10n + 5n);   // 15n   (OK: both BigInt)
console.log(10n + 5);    // TypeError: Cannot mix BigInt and other types

Most everyday programs never need BigInt. It appears in things like huge IDs, cryptography and exact calculations with giant numbers.

typeof cheat sheet

console.log(typeof "Hello");      // "string"
console.log(typeof 42);           // "number"
console.log(typeof 3.14);         // "number"
console.log(typeof NaN);          // "number"
console.log(typeof true);         // "boolean"
console.log(typeof undefined);    // "undefined"
console.log(typeof null);         // "object"  (old bug)
console.log(typeof 10n);          // "bigint"

// A sneak peek at what comes later:
console.log(typeof [1, 2, 3]);    // "object"  (arrays are objects)
console.log(typeof { a: 1 });     // "object"
console.log(typeof function () {}); // "function"

JavaScript is dynamically typed

In some languages, you must decide the type of a variable forever. In JavaScript, the variable has no fixed type. The value does. The same let variable can hold different types at different times:

let data = "Hello";
console.log(typeof data);   // "string"

data = 100;
console.log(typeof data);   // "number"

data = true;
console.log(typeof data);   // "boolean"

This is flexible, but it also means you must be careful. A variable might hold a type you did not expect.

Watch out: JavaScript may convert types for you

console.log("5" + 1);    // "51"  (number 1 became text, then joined)
console.log("5" - 1);    // 4     (text "5" became a number, then subtracted)

The + joins text, while - only does maths. This automatic conversion is called type coercion, and it is one of the most common sources of confusing bugs. You will see more of it in the operators lesson.

Common mistakes

  • Putting numbers in quotes. "25" is a string. "25" + 5 gives "255", not 30.
  • Writing True, FALSE or "true". The booleans are lowercase true and false, without quotes.
  • Confusing null and undefined. undefined is JavaScript’s default “no value”. null is what you assign yourself.
  • Trusting typeof null. It says "object", but null is a primitive.
  • Expecting 0.1 + 0.2 to equal 0.3. Round the result when exactness matters.
  • Mixing BigInt and number. 10n + 5 throws an error. Convert one of them first.
  • Forgetting that NaN is a number. typeof NaN is "number", so typeof cannot tell you if a calculation failed.

Practice

  1. In the editor, create one variable of each type: a string, a number, a boolean, undefined and null. Print each with its typeof.
  2. Predict the result, then check: typeof "42", typeof 42, typeof "true", typeof true.
  3. Print the result of "10" + 5 and "10" - 5. Why are they different?
  4. Print 0.1 + 0.2. Then print (0.1 + 0.2).toFixed(2). What does toFixed(2) do?
  5. Create a BigInt with the value 12345678901234567890, and try adding a normal number 1 to it. Read the error, then fix it by using 1n.

Recap

  • Every value has a type. Check it with typeof.
  • The main primitive types are string, number, boolean, null, undefined and bigint (plus symbol).
  • A string is text in quotes. A number covers both whole numbers and decimals, including Infinity and NaN. A boolean is true or false.
  • undefined is “no value yet” (set by JavaScript). null is “empty on purpose” (set by you).
  • typeof null returns "object", which is an old bug.
  • BigInt (with an n suffix) stores very large whole numbers and cannot be mixed with normal numbers.
  • JavaScript is dynamically typed: the value has a type, not the variable.
  • Next you will learn the operators that let you calculate, compare and combine these values.