How to Write Faster JavaScript Condition Expressions

    Craig Buckler

    There’s an interesting optimization feature in JavaScript which doesn’t necessarily apply in other languages. Consider the following code sample:

    var x = 10;
    var y = true;
    if (x*x > 1000 || y) alert("true!");

    As you’d expect, “true” is output because y is true — even though the first condition fails.

    JavaScript interpreters analyze each condition in sequence. If we changed x to 100, x*x would be greater than 1000 and evaluate to true. But, because we’re using a logical OR (||), the interpreter never needs to analyze y — the expression must be true so the alert is displayed.

    Therefore, we can optimize expressions to ensure those which require the least processing are analyzed first, i.e.

    if (y || x*x > 1000) alert("true!");

    If y is true, the interpreter will never need to evaluate the second condition. That could save considerable time, especially if we were calling a function, performing intensive calculations or analyzing the DOM.

    The same optimization applies to logical AND (&&). In that case, the first expression which evaluates to false makes the whole condition false — no further processing is required.

    Assignments inside conditions

    James Edwards recently wrote the article Assignment inside a Condition where he discussed code such as…

    if (summary = document.getElementById("post-summary")) {

    The summary variable is set to the HTML element with an ID of “post-summary”. If the element exists, the condition evaluates to true and the alert appears. If an element cannot be found, the condition evaluates to false and none of the conditional code is executed.

    It’s a useful technique although, according to the comments, few developers liked the practice because it makes JavaScript more difficult to read and debug.

    However, there’s another issue — with 2 or more conditions, your assignment may never execute. For example:

    if (x || y = functionY()) {

    If x evaluates to true, the interpreter never assigns a value to y and the alert will always throw an error.

    We could fix it by reversing the conditions so y is always evaluated, e.g.

    if (y = functionY() || x) …

    Even then, it could still cause confusion because it’s not obvious that the ordering of these conditions is essential. A developer who read the top half of this article might even attempt to optimize the code by evaluating x first!

    In summary, if you want to use assignments inside conditions, go ahead — but be absolutely sure it’s the only condition you’ll ever need!