AI Hints
JavaScript · Lesson 16 of 138

typeof

What type is it?.

⏱ 2 min read▶ Video at 18:12🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

Every value in JavaScript has a type. Number, string, boolean, and a few more. When you're not sure what you're dealing with, typeof tells you.

typeof
From the video: typeof
  • Every value has a type
  • Not sure which?
  • typeof tells you

Checking types

Typeof goes in front of a value, and gives its type as a string. Run it. Numbers, strings, booleans, and undefined all report what you'd expect. But null says object. That's a famous old bug in JavaScript, kept forever so old websites don't break.

app.jsjavascript
console.log(typeof 42);
console.log(typeof "hello");
console.log(typeof true);
console.log(typeof undefined);
console.log(typeof null);
Output
number
string
boolean
undefined
object

The basic types

JavaScript's basic types, called primitives, are number, string, boolean, undefined, and null. There are also big int, for huge whole numbers, and symbol, for unique labels, but you'll rarely need them as a beginner. Everything else, like lists and objects, is an object.

TypeExample
number42, 3.14
string"hello"
booleantrue, false
undefinednot set
nullempty on purpose
objectarrays, objects, more

More typeof results

Typeof works on any value. Arrays and objects both report object, because an array is a special kind of object. Functions report function. And typeof is handy for checking input before you use it, like making sure a value really is a number. Run it.

app.jsjavascript
console.log(typeof [1, 2, 3]);
console.log(typeof { name: "Ana" });
console.log(typeof function () {});

const input = "42";
if (typeof input !== "number") {
  console.log("Expected a number, got a", typeof input);
}
Output
object
object
function
Expected a number, got a string

Summary

Typeof reports a value's type. Remember the quirk, typeof null is object. Next, converting between types on purpose.

Key takeaways
  • typeof value
  • Five primitives
  • typeof null is 'object'
Next up: Converting Types — Number(), String()