say, you want to apply a method from the element proto on an element that may or may not be in the dom.
typically, I used to do:
var foo = document.getElementById("foo"); // or $("foo") for mootools/prototype, whatever
if (foo)
foo.focus();
though i now thought that due to flasy null and lazy &&, it can actually be written as:
var foo = document.getElementById("foo");
foo && foo.focus();
similarly:
var clickHandler = function(event) {
event && event.foo && event.foo();
};
clickHandler({
foo: function() { alert("bar"); }
});
clickHandler();
I have not seen this used much or at all as a pattern, which leads me to believe that it is:
- bad for readability purposes (not to me anyway)
- has cases where it will fail
Am I safe to continue using it?
http://jsfiddle.net/td6We/1/ to play with. I can’t seem to break it…
Is it safe?
yes in the context of the code being able to execute. The return mechanism of
||and&&is consistent and well-defined. It may not be safe to use around programmers who don’t understand the behavior of||and&&in JS.Is it readable?
It depends on what you’re doing. For cases where you’re performing an action on a dom element, I highly recommend using an
ifstatement. It’s very easy for a single statement to turn into multiple for cross-browser usage:might turn into
at which point it’s much more legible as:
However there are niche cases where it’s not likely going to turn into more. I use this particular statement style all the time: