Can typeof return a falsey value?

Viewed 120

I stumbled over some interesting code inside react. Link to code

if (typeof data[Symbol.iterator]) { ... }

In my understanding typeof[data[Symbol.iterator]] should be truthy because typeof returns a string. like:

const obj = {}
if(typeof(obj.x)){
  console.log("hello world");
}

gives out “hello world” because even typeof(undefined) => "undefined" => truthy

tldr: Is there any possible falsey outcome of typeof?

1 Answers

As described here :

Errors Before ECMAScript 2015, typeof was always guaranteed to return a string for any operand it was supplied with. Even with undeclared identifiers, typeof will return 'undefined'. Using typeof could never generate an error.

But with the addition of block-scoped let and Statements/const using typeof on let and const variables (or using typeof on a class) in a block before they are declared will throw a ReferenceError. Block scoped variables are in a "temporal dead zone" from the start of the block until the initialization is processed, during which, it will throw an error if accessed.

typeof undeclaredVariable === 'undefined';

typeof newLetVariable; // ReferenceError
typeof newConstVariable; // ReferenceError
typeof newClass; // ReferenceError

let newLetVariable;
const newConstVariable = 'hello';
class newClass{};

In general, typeof() will return a string and thus if checked in a condition alone will always be truthy. If you want to check a variable and verify if its undefined (or any other state), you can use a condition like : typeof(undefinedvariable) == "undefined"

Related