Skip to content Skip to sidebar Skip to footer

Optimizing Conditionals/if Blocks, What Is Preferable From A Performance Point Of View?

I am writing a JS library, and there are two things that have been on my mind for quite some time though. Consider an option: var option = { bool : true } ; Now, imagine I do ei

Solution 1:

The answer is simple. It's less about coding patterns and more about logic. In this scenario there are always 3 possibilities and you need to cater for each of them. Ie. 1. TRUE 2. FALSE 3. undefined If the value is undefined then do you want it to fall under the true or false clause? OR should it be catered for differently?

Another important thing to remember is that if it is undefined then it will always execute the code in the false clause. Is that what you want?

If you know that the value will always be either true or false then I suggest that you still use the syntax == true as this is more readable. Someone browsing over the code would know that you are looking for the boolean value and not testing if the field has been set.

You have to think about these 3 cases every time you have a boolean in an if statement, so there is no 1 answer for you.

Post a Comment for "Optimizing Conditionals/if Blocks, What Is Preferable From A Performance Point Of View?"