What's the equivalent of .get in javascript?
You have (at least) four options:
In many cases, you can use the curiously-powerful
||
operator:x = obj.key || "default";
That means: Set
x
toobj.key
unlessobj.key
is falsy, in which case use"default"
instead. The falsy values areundefined
,null
,0
,NaN
,""
, and of course,false
. So you wouldn't want to use it ifobj.key
may validly be0
or any other of those values.For situations where
||
isn't applicable, there's thein
operator:x = "key" in obj ? obj.key : "default";
in
tells us whether an object has a property with the given key. Note the key is a string (property names are strings or Symbols; if you were using a Symbol, you'd know). So ifobj.key
may be validly0
, you'd want to use this rather than #1 above.in
will find a key if it's in the object or the object's prototype chain (e.g., all of the places you'd get it from if you retrieve the property). If you just want to check the object itself and not its prototype chain, you can usehasOwnProperty
:x = obj.hasOwnProperty("key") ? obj.key : "default";
Specifically check for
undefined
:x = typeof obj.key !== "undefined" ? obj.key : "default";
That will use the default if
obj
doesn't have that property or if it has the property, but the property's value isundefined
.
Javascript's logical OR operator is short-circuiting. You can do:
d["hello"] || "default_val";