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");
}
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.
The only case where typeof varName === 'undefined' is useful is when you don't know whether the variable varName has been declared.
And IMO if you don't know whether your variables are declared, your code has serious problems.
In other cases you have better options:
varName === void 0This will detect whether
varNameis undefined.voidis an operator which receives an argument (you can use whatever instead of0), and returns undefined.varName === undefinedThis should detect whether
varNameis undefined.However, be aware the global
undefinedcould have been overwritten (before ES5) or shadowed with another value. Therefore I prefervoid, which is also shorter.varName == nullThis will detect whether
varNameis undefined or is null.!varNameThis will detect whether
varNameis falsy (undefined, null, 0, empty string, NaN, false).
来源:https://stackoverflow.com/questions/34596489/es2015-2016-way-of-typeof-varname-undefined