K. Michael
K. Michael

Reputation: 75

When using a switch statement in Javascript with multiple cases, how can I refer to a case?

So I have some code:

var Animal = 'Giraffe';
switch (Animal) {
  case 'Cow':
  case 'Giraffe':
  case 'Dog':
  case 'Pig':
    console.log('This animal will go on Noah\'s Ark.');
    break;
  case 'Dinosaur':
  default:
    console.log('This animal will not.');
}

Ideally, I'd like the first console.log to print "This Giraffe will go on Noah's Ark", or whatever the variable Animal happened to be. I want to refer to the case. However, I'm not sure how to write that code. Can someone help?

Upvotes: 0

Views: 143

Answers (3)

Dan Field
Dan Field

Reputation: 21661

Just use your variable:

var Animal = 'Giraffe';
switch (Animal) {
  case 'Cow':
  case 'Giraffe':
  case 'Dog':
  case 'Pig':
    console.log('This ' + Animal + ' will go on Noah\'s Ark.');
    break;
  case 'Dinosaur':
  default:
    console.log('This animal will not.');
}

(note: I'm using string concatenation here under the assumption that you may actually want to do something other than use the console.log function to do something like this - if you really just want to use console.log, it may be more reasonable to use one of the other answers provided)

Upvotes: 1

Roko C. Buljan
Roko C. Buljan

Reputation: 206347

You could use a token %s (string in this case) and than after a comma use your variable:

var Animal = 'Giraffe';
switch (Animal) {
  case 'Cow':
  case 'Giraffe':
  case 'Dog':
  case 'Pig':
    console.log('This %s will go on Noah\'s Ark.', Animal);
    break;
  case 'Dinosaur':
  default:
    console.log('%s will not.', Animal);
}

Upvotes: 2

Daniel A. White
Daniel A. White

Reputation: 190976

Just use additional arguments to log and Animal.

console.log('This', Animal, 'will go on Noah\'s Ark.');

Upvotes: 2

Related Questions