It's actually really unclear how to do such checks, you have to keep in mind what failures you actually expect to have.
On one hand, if you expect an object, truthiness gets rid of null, undefined, false (we'd be getting the false from the typeof equality, as well as hasOwnProperty) as well as less importantly 0, and "".
// OH NO;({location:undefined}.hasOwnProperty("location"))// true;({location:null}.hasOwnProperty("location"))// true// Better I guess!!({location:undefined}).location// false
But on the other hand, if you expect a number, you will have weird failure on 0, which is very commonly a normal number. In which case you often check for undefined.
constfn1=(num=1)=>num// How would we write this without default notation?constfn2=num=>num||1// NO, YOU DIE!constfn3=num=>(num===undefined?1:num)// it's okay to not use typeof x === "undefined" in this context, it's a declared argument.
But it doesn't solve everything!
constwindow={location:{hostname:{valueOf:()=>"localhost"}}}consthostname=typeofwindow!=="undefined"&&window.location&&window.location.hostname""+hostname==="localhost"// The triple equals won't save you now, once string concatenation happened!
Maybe we should always use typeof :/
But what is your next action if hostname is an object? Pretending it wasn't set and defaulting to secure?
Honestly, truthiness seems like the best bet to me, I just need to keep track of when it can be a 0 or "" or a literal significant false and it'll be okay.
I think I'll just keep using that.
>(undefined).potatoes//TypeError: Cannot read property 'potatoes' of undefined>(null).potatoes//TypeError: Cannot read property 'potatoes' of null>(true).potatoesundefined// And it will never be anything truthy on a non-object, right? RIGHT?>(true).valueOf[Function:valueOf]// OH GOD DAMMIT!!
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
So then, something like this?
I guess.
It's actually really unclear how to do such checks, you have to keep in mind what failures you actually expect to have.
On one hand, if you expect an object, truthiness gets rid of
null
,undefined
,false
(we'd be getting thefalse
from the typeof equality, as well ashasOwnProperty
) as well as less importantly0
, and""
.But on the other hand, if you expect a number, you will have weird failure on
0
, which is very commonly a normal number. In which case you often check for undefined.But it doesn't solve everything!
Maybe we should always use
typeof
:/But what is your next action if
hostname
is an object? Pretending it wasn't set and defaulting to secure?Honestly, truthiness seems like the best bet to me, I just need to keep track of when it can be a
0
or""
or a literal significantfalse
and it'll be okay.I think I'll just keep using that.