How to create a CoffeeScript style existential operator in JavaScript?
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.
Very old question but made me thinking about this solution.
exists = (obj) => obj || {}
exists(nullableObject).propName;