Skip to content
  • Data Types & typeof · JavaScript

Data Types & typeof

LearnViaNotes @learnvianotes· 2 min read

Seven primitive types plus objects. Values have types; variables do not.

The eight types

TypeExamplestypeof
Number42, 3.14, -0, NaN, Infinity"number"
BigInt9007199254740993n"bigint"
String'hi', "hi", template literals with backticks"string"
Booleantrue, false"boolean"
Undefinedundefined — declared but no value"undefined"
Nullnull — intentional “no value”"object" (historic bug!)
SymbolSymbol('id') — unique key"symbol"
Object{}, [], functions, dates, maps…"object" / "function"

typeof in practice

JavaScript
console.log(typeof 42, typeof 10n, typeof "s", typeof true);
console.log(typeof undefined, typeof Symbol(), typeof {}, typeof []);
console.log(typeof null);                 // the famous bug
console.log(typeof function () {}, typeof class {});
console.log(typeof notDeclaredAnywhere);  // no ReferenceError
Output
number bigint string boolean
undefined symbol object object
object
function function
undefined

Checking types reliably

QuestionUse
Is it an array?Array.isArray(x) (not typeof)
Is it null?x === null
Null or undefined?x == null (the one accepted use of ==) or x ?? fallback
Instance of a class?x instanceof Date (walks the prototype chain)
Exact built-in tag?Object.prototype.toString.call(x)
Is it NaN?Number.isNaN(x)
JavaScript
const tag = (x) => Object.prototype.toString.call(x);
console.log(Array.isArray([]), [] instanceof Array);
console.log(tag(null), tag([]), tag(new Date(0)), tag(/re/));
Output
true true
[object Null] [object Array] [object Date] [object RegExp]

undefined vs null

JavaScript
let a;
const obj = {};
function f() {}
console.log(a, obj.missing, f());
console.log(null == undefined, null === undefined);
console.log(Number(null), Number(undefined));
Output
undefined undefined undefined
true false
0 NaN

Dynamic typing

JavaScript
let value = 10;
console.log(typeof value);
value = "ten";
console.log(typeof value);
value = [10];
console.log(typeof value, Array.isArray(value));
Output
number
string
object true

How many data types does JavaScript have?

Why does typeof null return "object"?

Free for students and teachers

Write notes like this one

Cards for every idea, quizzes and flashcards, read aloud — on the web and your phone.

Something wrong with this note? Open it to report