JavaScript Switch VS. If...Else If...Else

Javascript switch vs. if...else if...else

Answering in generalities:

  1. Yes, usually.
  2. See More Info Here
  3. Yes, because each has a different JS processing engine, however, in running a test on the site below, the switch always out performed the if, elseif on a large number of iterations.

Test site

When to use If-else if-else over switch statements and vice versa

As with most things you should pick which to use based on the context and what is conceptually the correct way to go. A switch is really saying "pick one of these based on this variables value" but an if statement is just a series of boolean checks.

As an example, if you were doing:

int value = // some value
if (value == 1) {
doThis();
} else if (value == 2) {
doThat();
} else {
doTheOther();
}

This would be much better represented as a switch as it then makes it immediately obviously that the choice of action is occurring based on the value of "value" and not some arbitrary test.

Also, if you find yourself writing switches and if-elses and using an OO language you should be considering getting rid of them and using polymorphism to achieve the same result if possible.

Finally, regarding switch taking longer to type, I can't remember who said it but I did once read someone ask "is your typing speed really the thing that affects how quickly you code?" (paraphrased)

javascript switch() or if()

You might use switch if you foresaw needing to add lots of new cases.

If you won't be adding many new cases, I might do, for clarity:

is_valid.accepted = message=='redirect';

(also note that your check for 'invalid id' does nothing)

Nevertheless if you had to add new things, notice how it's good you don't have to repeat yourself don't have to repeat yourself don't have to repeat yourself, also the sexy formatting:

switch (message)
{
case 'invalid id':
case 'penguin invasion':
case 'the internet is down':
case 'error not enough caffeine':
is_valid.accepted = false;
break;

case 'redirect':
case 'upvote me':
case 'vip':
case 'flamewar':
is_valid.accepted = true;
break;

default:
is_valid.accepted = false;
// perhaps log or something
}

Imagine all those ugly else and else-ifs you'd have otherwise.


sidenote:
If you had really complicated rules, but still a whitelist-blacklist-on-a-single-flag paradigm, then:

var blacklist = ['invalid id', 'penguin invasion', 'the internet is down' 'error not enough caffeine'];
var whitelist = ['redirect', 'upvote me', 'vip', 'flamewar'];

is_valid.accepted = whitelist.indexOf(message)!=-1;

You might also do this if you wanted to dynamically construct your whitelist.

If else and switch case alternative in Javascript

You could move some logic into configuration. Try to harmonise checks such that they all depend on regular expressions. So for a minimum length of 6, use /....../ as regular expression. Also make sure the regular expression will not accept an empty string in case the field is considered required.

For example:

// All specifics are encoded here:
const checks = [
{ field: "email", regex: /^\S+@\S+\.\S+$/, name: "Email address", msg: "must be 6 or more characters" },
{ field: "password", regex: /....../, name: "Password", msg: "is invalid" },
];

// ...while this is now (more) generic:
function validate(values) {
const errors = {};
for (const {field, regex, name, msg} of checks) {
if (!regex.test(values[field])) {
errors[field] = name + " " + (values[field] ? msg : "is required");
}
}
return errors;
}

Javascript switch versus if/else

Really, the question as it stands is flawed. The course you're taking is an Introduction to Objects, so why both with arrays that aren't associative? Simply:

movieReviews = { 
"matrix": "a good trip"
}
// These are now both valid for accessing "a good trip"
movieReviews["matrix"];
movieReviews.matrix

Every movie is going to have a unique name, which makes it a perfect candidate for a key. Furthermore, the function used for searching for reviews should be a method of the review object. For what it's worth (and hopefully it's something, even if not right now), this is how I would implement the solution.

MovieReviews = function() {
/* Private data. */
var data = {
"matrix": "good trip out",
"Princess Bride": "awesome date night movie",
"Welcome to America": "Amjad's favorite"
}
/* Get a review for a movie by name, or notify that we don't know */
this.getReview = function(movie) {
if(data.hasOwnProperty(movie)) { return data[movie]; }
return "I don't know!";
}
/* Add a review by movie name, and review string. */
this.addReview = function(movie, review) {
data[movie] = review;
}
}

Now instantiate a new MovieReview object, add a new movie review, and print some tests.

var reviews = new MovieReviews();
reviews.addReview("Remember the Titans", "love the sports");

console.log(reviews.getReview("matrix")); // 'good trip out'
console.log(reviews.getReview("Remember the Titans")); // 'love the sports'
console.log(reviews.getReview("A Scanner Darkly")); // 'I don't know!'

This way accessing your reviews for each movie is trivial, and requires no iteration at all. You are also containing your data within an object, providing encapsulation and forcing users to use your interfaces.

As for your original question, it's hard for me to say whether and if-else or switch statement would be more efficient without performing some timed tests (maybe something you could do and let us know!). But based on what's written here,

"If multiple cases match the provided value, the first case that matches is selected..."

this seems like it's just iterating through the cases anyway. How the JavaScript control structures are translated with your current JS engine probably optimises your switch statement, and I would bet that it performs better over if-else with a large quantities of options.

Performance aside, it's much nice reading a switch statement that has many elements, compared to an if-else. Also, there are often time when you can change other factors like your object types (array -> object in my example), to better fix an issue.

Don't get caught in the trap of prematurely optimising your code, or else you'll never get anything finished and people that maintain your work will hate you, forever, and ever.

Is there any performance gain from using a switch statement over a bunch of if()else if() in javascript?

In general, switch is faster than if - else if statements.

However, kind of best practice is to use if - else if if you got max 3 conditionals. If you're going beyond that, you should use switch statements.

The problem with if else is that it possibly needs to check multiple times before it finally reaches the code to execute. Therefore you also need to optimize the order for your conditional statements.

if( foo ) {
}
else if( bar ) {
}
else if( baz ) {
}

That code would not make much sense from a performance prospective if you expect baz to be true and foo/bar to be false most of the times.

switch vs if-else branching control structure in Node.JS

For just a few items, the difference is small. If you have many items you should definitely use a switch. It give better performance than if-else.

If a switch contains more than five items, it's implemented using a lookup table or a hash list. This means that all items get the same access time, compared to a list of if-else where the last item takes much more time to reach as it has to evaluate every previous condition first..

Performance of if-else, switch or map based conditioning

According to this JSBen.ch test, the switch setup is the fastest out of the provided methods (Firefox 8.0 and Chromium 15).

Methods 3 and 4 are slightly less fast, but it's hardly noticeable. Clearly, the if-elseif method is significantly slower (FireFox 8.0).

The same test in Chromium 15 does not show significant differences in performance between these methods. In fact, the if-elseif method seems to be the fastest method in Chrome.

Update

I have run the test cases again, with 10 additional entries. The hrefmap (methods 3 and 4) show a better performance.

If you want to implement the compare method in a function, method 3 would definitely win: Store the map in a variable, and refer to this variable at a later point, instead of reconstructing it.



Related Topics



Leave a reply



Submit