CoffeeScript turns user?.id
into
if (typeof user !== "undefined" && user !== null) {
user.id;
}
Is it possible to create a JavaScript function exists
that would do something similar? i.e.
exists(user).id
would result in either user.id
or null
It would be easier if a function accepts another parameter, i.e. exists(user, 'id')
, but that wouldn't look as nice.
No, you can't produce such a function. The problem is that this:
any_function(undeclared_variable)
will produce a ReferenceError if undeclared_variable
was not declared anywhere. For example, if you run this stand alone code:
function f() { }
f(pancakes);
you'll get a ReferenceError because pancakes
was not declared anywhere. Demo: http://jsfiddle.net/ambiguous/wSZaL/
However, the typeof
operator can be used on something that has not been declared so this:
console.log(typeof pancakes);
will simply log an undefined
in the console. Demo: http://jsfiddle.net/ambiguous/et2Nv/
If you don't mind possible ReferenceErrors then you already have the necessary function in your question:
function exists(obj, key) {
if (typeof obj !== "undefined" && obj !== null)
return obj[key];
return null; // Maybe you'd want undefined instead
}
or, since you don't need to be able to use typeof
on undeclared variables here, you can simplify it down to:
function exists(obj, key) {
if(obj != null)
return obj[key];
return null;
}
Note the change to !=
, undefined == null
is true even though undefined === null
is not.
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