samrap
samrap

Reputation: 5673

If/and/if statement in JavaScript

I had a quick question about performance in a javascript code. For example, say I had a function with a parameter and some if statements inside:

function myFunction(a,b,c) {
    if(condition) {
        //execute
    } else { 
        //execute
    }
}

In this particular case I need to compare multiple conditions in my if statement. Based on my understanding, there are two ways to do this:

function myFunction(a,b,c) {
    if(a === b && b === c) {
        //execute
    } else { 
        //execute
    }
}

or:

function myFunction(a,b,c) {
    if (a === b) {
      if (b === c) {
        //execute
    } else {
        //execute
    }
}
}

My question is, based on performance, which is better to use. Clarification: this question is NOT based on opinionated answers, it is strictly based on the question are there any possible issues that could arise using one or the other? For example, you don't have to declare a variable using the var keyword, but problems could arise (between global and local variables under the same name) if you don't. Could a problem similar to the variable example arise in any of these two if/and statements?

Upvotes: 1

Views: 196

Answers (2)

Guffa
Guffa

Reputation: 700212

Your performance question is moot, as the different ways of writing the code gives different results.

With the second way of writing it, the else block is only executed when a !== b, but not when a === b and b !== c.


Ignoring the else part, you would get very similar performance with the difference codes, as they do the same thing. Performance will vary between browsers, and even between different versions of the same browser, so even if you find that one method is often faster in most of the current browsers, that could very well change in a near future.

Both methods works well, and doesn't have any nasty performance issues, so you should simply use the one that most clearly resembles the intention of the code.

Upvotes: 3

tom
tom

Reputation: 718

You can use console.time('name') and console.timeEnd('name') to check performance in JS.

Made a fiddle demonstrating: http://jsfiddle.net/bwYT7/

Upvotes: 1

Related Questions