CodeMIRAI
0 XP

Data types

2 min read 5 runnable examples Quiz included

JavaScript values come in a handful of types. Seven are primitive (simple values), and everything else is an object.

TypeExample
number42, 3.14, -7, NaN
string"hello", 'hi', or a template literal in backticks
booleantrue, false
undefineda variable with no value yet
null"intentionally empty"
bigint123n, for huge integers
symbolunique identifiers (advanced)
object{}, [], functions, dates...

typeof

JavaScript
console.log(typeof 42);
console.log(typeof "hi");
console.log(typeof true);
console.log(typeof undefined);
console.log(typeof { a: 1 });
console.log(typeof [1, 2]);       // arrays are objects
console.log(typeof null);         // a famous historical bug: "object"

One number type

JavaScript has a single number type for both whole numbers and decimals:

JavaScript
console.log(7 / 2);
console.log(0.1 + 0.2);
console.log(10 / 0);
console.log("abc" * 2);      // NaN: "Not a Number"
console.log(Number.isNaN("abc" * 2));

undefined vs null

  • undefined means "no value has been given yet". JavaScript uses it automatically.
  • null means "deliberately empty". You set it yourself.
JavaScript
let notSetYet;
let emptyOnPurpose = null;
console.log(notSetYet, emptyOnPurpose);

Type conversion and the == trap

JavaScript converts types automatically in some situations, and the results can be surprising:

JavaScript
console.log("5" + 3);     // "53": + with a string joins
console.log("5" - 3);     // 2: - converts to numbers
console.log("5" == 5);    // true: == converts before comparing
console.log("5" === 5);   // false: === compares type AND value
console.log(0 == "");     // true (!)
console.log(0 === "");    // false

Converting on purpose

JavaScript
console.log(Number("42"), Number("4.5"), Number("abc"));
console.log(parseInt("42px"), parseFloat("3.5kg"));
console.log(String(99), (99).toString());
console.log(Boolean(""), Boolean("hi"), Boolean(0));
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.