Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a CoffeeScript style existential operator in JavaScript?

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.

like image 723
kqw Avatar asked Jun 27 '13 11:06

kqw


1 Answers

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.

like image 97
mu is too short Avatar answered Oct 19 '22 20:10

mu is too short