Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

More efficient way than using lots of else if statements

I'm trying to find a better way to do this in Javascript:

if ( text === 'amy' ) {
var url = 'http://www.mydomain.com/amylikescats.html';
}
else if ( text === 'dave' ) {
var url = 'http://www.mydomain.com/daveshome.html';
}
else if ( text === 'steve' ) {
var url = 'http://www.mydomain.com/steve2.html';
}
else if ( text === 'jake' ) {
var url = 'http://www.mydomain.com/jakeeatstofu.html';
}
else {
var url = 'http://www.mydomain.com/noone.html';
}

Is there a more code efficient way of doing this?'

like image 950
Cheeky Cherub Avatar asked Nov 28 '25 06:11

Cheeky Cherub


2 Answers

Use an object as a map:

var map = {
    "amy": 'http://www.mydomain.com/amylikescats.html',
    "dave": 'http://www.mydomain.com/daveshome.html',
    // etc
};

var text = "whatever";
var url = map[text] === undefined ? 'http://www.mydomain.com/noone.html' : map[text];

This will save you the maximum amount of repeated code, but if you also need to do other stuff than setting url a switch might be more appropriate.

like image 165
Jon Avatar answered Nov 30 '25 21:11

Jon


Switch statement!

var url = 'http://www.mydomain.com/noone.html';
switch(text) {
  case 'amy': url = 'http://www.mydomain.com/amylikescats.html';
  break;
  case 'dave': url = 'http://www.mydomain.com/daveshome.html';
  break;
  case 'steve': url = 'http://www.mydomain.com/steve2.html';
  break;
  case 'jake': url = 'http://www.mydomain.com/jakeeatstofu.html';
  break;
}

Now there is no need for a default clause because you've initialized url before the switch.

Otherwise you could add this:

default: url = 'http://www.mydomain.com/noone.html';
break;
like image 36
Aesthete Avatar answered Nov 30 '25 19:11

Aesthete



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!