Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES2015/2016 way of 'typeof varName === 'undefined`?

I'm wallowing in ES2015+ luxury with a few projects right now and am wondering whether I can get rid of the much hated crutch to check for undefined in the new wonderland.

Is there a shorter but still exact way to typeof varName === 'undefined' in ES2015+ already?

Of course I could use default parameters but this also feels like an unnecessary assignment.

function coolFn(a = null){    if (a===null) console.log("no a supplied"); } 
like image 493
Hedge Avatar asked Jan 04 '16 17:01

Hedge


People also ask

What is the value of typeof undefined == typeof null?

Referencing undeclared variables usually results in a ReferenceError, except when using the typeof keyword. The typeof undefined is the string "undefined" — and undefined is a falsy value that is loosely equal to null but not to other falsy values.

Why typeof undefined is undefined?

This is due to the fact that the typeof operator returns the string undefined when a variable is not declared or currently hold the value undefined which is exactly what we want.

How do you know if typeof is undefined?

In a JavaScript program, the correct way to check if an object property is undefined is to use the typeof operator. If the value is not defined, typeof returns the 'undefined' string.


1 Answers

Just check for varName === undefined.

In older browsers it was possible to assign an alternate value to the global undefined variable causing that test to fail, but in ES2015+ that's now impossible.

Note that there's no way to distinguish explicitly passing undefined as a parameter from leaving the parameter out altogether other than by looking at arguments.length.

like image 152
Alnitak Avatar answered Sep 29 '22 22:09

Alnitak