liveBook · Manning

Typeof operator

As explained in Secrets of the JavaScript Ninja, Third Edition

The JavaScript typeof operator returns a string indicating the basic type of its operand.

JavaScript’s `typeof` operator returns a string describing an operand’s basic type. It also lets you test whether a possibly undeclared global exists: `typeof ninjaName` returns `"undefined"` instead of throwing a `ReferenceError`. section 7.4 section 9.4.1

Check before initializing a global

Use `typeof ninjaName === "undefined"` before assigning to `globalThis.ninjaName`. For a declared global, this check is generally equivalent to `ninjaName === undefined`; for an undeclared global, the direct reference throws. section 7.4

const initializeGlobalName = () => {
  if (typeof ninjaName === "undefined") {
    globalThis.ninjaName = "Naruto";
  }
}

A short example uses typeof to initialize a global only when it is undefined. section 7.4

This check does not avoid the Temporal Dead Zone for an uninitialized local variable: `typeof` can still throw a `ReferenceError`. Also, `typeof` reports class instances as `"object"`; it does not identify their class. section 7.4 section 9.4.1

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Explains global checks, comparison with undefined, and the local-variable Temporal Dead Zone, without detailing all return values.
Examples
Uses a typeof guard before assigning a global and contrasts typeof on a class instance with instanceof.
What it assumes
Uses global and local scope, variable declarations, and ReferenceError without establishing them from zero.
What you can do after
Diagnose whether a global identifier is undeclared and recognize when typeof cannot safely check a local variable.
How it connects
Connects to global scope, scope chains, the Temporal Dead Zone, and JavaScript classes.

Also explained in

Compare how 4 books explain typeof operator →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Third Edition. The section links point to the parts of the book it draws on.