Primitive Types

JavaScript primitive types are string, number, boolean, null, undefined, symbol, and bigint. Their names are mostly self-explanatory, but there are still a few details worth paying attention to:

  • JavaScript does not distinguish between int, float, and double. All numeric values are represented as number.
  • If you declare a variable like let z, its value is undefined.
  • undefined means a value is missing by default. null means you intentionally assign an empty value. In practice, we usually do not intentionally set values to undefined; we mostly handle it when a function returns undefined.
  • bigint is designed for integers outside the safe range of number. A regular number can safely represent values in the range -(2^53) to 2^53 - 1, while bigint is theoretically unbounded and only limited by memory.
const username = "Kayn";
const age = 17;
const GPA = 4.99;
const male = true;
const x = null;
const y = undefined;
let z;

Dynamic Typing

JavaScript is dynamically typed. For example:

let x = 10; // x is a number
x = "hello"; // now x is a string
x = true; // now x is a boolean

Pros and Cons

One advantage is that you do not always need explicit conversion:

let x = "5";
console.log(x * 2); // 10

In a statically typed language like Java, you would usually need:

Integer.parseInt("5") * 2

However, dynamic typing can also produce results you do not want:

let x = "5";
console.log(10 + x); // "105"

In Java, similar code would be caught by the IDE or compiler much earlier.

In real engineering work, it is often better to accept a bit more ceremony and reduce the chance of mistakes, especially in team projects. That is one reason TypeScript exists: it makes JavaScript more suitable for larger-scale engineering.

Getting the Type of a Value

Because variable types can change at runtime, JavaScript provides the typeof operator:

typeof 123; // "number"
typeof "hello"; // "string"
typeof undefined; // "undefined"

One interesting case is:

typeof null; // "object"

This is considered a historical quirk in JavaScript. The reason is:

  • Early JavaScript stored values using a mechanism similar to a tagged union, where each value had a type tag.
  • Objects used the type tag 0.
  • null was mistakenly assigned the same tag 0.
  • As a result, typeof null returns "object".

So in real code, if you need to check whether a value is null, use this instead:

let x = null;
console.log(x === null); // true