Data Types

The Eight Data Types

TypeExampleKind
String"Hello", 'A', `hi`primitive
Number42, 3.14, NaN, Infinityprimitive
BigInt9007199254740993nprimitive
Booleantrue, falseprimitive
undefineda declared variable with no valueprimitive
nullintentionally "no value"primitive
SymbolSymbol("id"): unique keysprimitive
Object{}, [], functions, dates...reference

Dynamic Typing

Example

A variable can hold any type, and the type can change:

let x = 42;
console.log(typeof x);
x = "forty-two";
console.log(typeof x);
x = [4, 2];
console.log(typeof x, Array.isArray(x));

Output

number
string
object true

Primitives vs References

Example

Primitives are copied by value; objects are copied by reference (both variables point to the same object):

let a = 10;
let b = a;
b = 20;
console.log(a, b);          // a is unchanged

const o1 = { score: 10 };
const o2 = o1;
o2.score = 20;
console.log(o1.score);      // o1 changed too: same object

Output

10 20
20