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:
int, float, and double. All numeric values are represented as number.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;JavaScript is dynamically typed. For example:
let x = 10; // x is a numberx = "hello"; // now x is a stringx = true; // now x is a booleanOne advantage is that you do not always need explicit conversion:
let x = "5";console.log(x * 2); // 10In a statically typed language like Java, you would usually need:
Integer.parseInt("5") * 2However, 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.
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:
0.null was mistakenly assigned the same tag 0.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