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"); }
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With