DEV Community

Discussion on: JavaScript Tip: whatis() — A better typeof

Collapse
 
savagepixie profile image
SavagePixie

The whatis() function will throw a ReferenceError for variables that have not been declared, unlike the typeof operator that evaluates to "undefined" for undeclared variables.

Why not add a test for undefined then?

function whatis (value) {
  return value === undefined
    ? undefined
    : Object.prototype.toString.call(value)
      .replace(/^\[object\s+([a-z]+)\]$/i, '$1')
      .toLowerCase();
}
Collapse
 
gladchinda profile image
Glad Chinda • Edited

Adding a test for undefined doesn't still solve the undeclared variable problem. In JavaScript, as much as I know, accessing an undeclared variable will always throw a ReferenceError. The only exception being with the typeof operator, where it evaluates to "undefined".

The typeof operator behaves such that it should never throw an error for any valid JavaScript value used as its operand, including an undeclared variable.

That said, running the modified function you defined above with an undeclared variable will still throw a ReferenceError.