JavaScript Types
JavaScript Types: The Complete Guide
JavaScript uses dynamic typing, where the type of a variable is automatically determined based on the value it holds. Types are divided into two main categories: primitive (value-based) and object (reference-based).
Represents numeric values, either integer or decimal.
Example:
let age = 25; // integer
let price = 9.99; // decimal
Special values:
Read more here
Textual data enclosed in single (''), double ("") quotes, or backticks (``).
Example:
let name = "Anna";
let message = `Hello, ${name}!`; // template string
Read more here
Has two values: true
(truthy) and false
(falsy).
Example:
let isOnline = true;
let hasPermission = false;
Read more here
Represents an empty or unknown value. Must be explicitly assigned.
Example:
let user = null; // user has no value
Read more here
Indicates a variable is declared but not assigned a value.
Example:
let score;
console.log(score); // undefined
Read more here
A unique value used for object property keys.
Example:
const id = Symbol("id");
Represents large integers by appending n
.
Example:
const bigNumber = 123456789012345678901234567890n;
Objects store complex data structures and are referenced by their memory location.
A collection of key-value pairs.
Example:
let person = {
name: "Karen",
age: 30
};
An ordered collection of elements accessible by index.
Example:
let colors = ["red", "blue", "green"];
A reusable block of code that can be invoked.
Example:
function add(a, b) {
return a + b;
}
Many other object types exist.
The typeof
operator returns the type as a string.
console.log(typeof 42); // "number"
console.log(typeof "Hello"); // "string"
console.log(typeof undefined); // "undefined"
instanceof
checks if an object belongs to a specific class.
console.log([] instanceof Array); // true
JavaScript automatically converts types during operations:
5 + "" → "5"
+"10" → 10
!!0 → false
, !!"text" → true
JavaScript manages memory differently based on types:
let a = 10;
let b = a; // Copies the value
a = 20;
console.log(b); // 10 (unchanged)
let obj1 = { name: "Anna" };
let obj2 = obj1; // Copies the reference
obj1.name = "Karen";
console.log(obj2.name); // "Karen" (modified)
===
(strict equality) instead of ==
to avoid type coercion.isNaN()
.let
and const
.