Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript && operator versus nested if statements: what is faster?

Now, before you all jump on me and say "you're over concerned about performance," let it hereby stand that I ask this more out of curiosity than rather an overzealous nature. That said...

I am curious if there is a performance difference between use of the && ("and") operator and nested if statements. Also, is there an actual processing difference? I.e., does && always process both statements, or will it stop @ the first one if the first one fails? How would that be different than nested if statements?

Examples to be clear:

A) && ("and") operator

if(a == b && c == d) { ...perform some code fashizzle... } 

versus B) nested if statements

if(a == b) {     if(c == d) { ...perform some code fashizzle... } } 
like image 679
americanyak Avatar asked Jun 27 '10 02:06

americanyak


People also ask

What is the JavaScript used for?

Javascript is used by programmers across the world to create dynamic and interactive web content like applications and browsers. JavaScript is so popular that it's the most used programming language in the world, used as a client-side programming language by 97.0% of all websites.

Is JavaScript a coding?

JavaScript is a lightweight interpreted programming language. The web browser receives the JavaScript code in its original text form and runs the script from that.

Is JavaScript easy to learn?

JavaScript is a simple and easy-to-learn programming language as compared to other languages such as C++, Ruby, and Python. It is a high-level, interpreted language that can easily be embedded with languages like HTML.

Is JavaScript and HTML the same?

Both of these are computer languages that help in programming, but there is a major difference between JavaScript and HTML. While JavaScript (abbreviated as JS) is a scripting language, HTML is a markup language. We use HTML to create web pages or web applications.


1 Answers

The performance difference is negligible. The && operator won't check the right hand expression when the left hand expression evaluates false. However, the & operator will check both regardless, maybe your confusion is caused by this fact.

In this particular example, I'd just choose the one using &&, since that's better readable.

like image 133
BalusC Avatar answered Sep 28 '22 10:09

BalusC