Sign in
Log inSign up

Why does "switch" not work in a route

Deactivated User's photo
Deactivated User
·Nov 24, 2018

I wanted to render some output to the browser when some params where matched, I tried using the switch syntax inside the route but it wouldn't work.

app.get('/speak/:animal', function (req, res) {
  var animal = req.params.animal
  var sound = {
     dog: 'woff woff',
     cat: 'meow',
     cow: 'moo'
  }

  switch (animal) {
    case animal === 'cat':
       res.send(`${animal} says: '${sound[animal]}'`)
       break;

   case animal === 'dog':
      res.send(`${animal} says: '${sound[animal]}'`)
       break;

  case animal === 'cow':
      res.send(`${animal} says: '${sound[animal]}'`)
       break;

  default:
     res.send('We did not cover this animal')
     break;
  }
})

But with an if/else block it works.

app.get('/speak/:animal', function (req, res) {
  var animal = req.params.animal
  var sound = {
     dog: 'woff woff',
     cat: 'meow',
     cow: 'moo'
  }

 if (animal === 'dog') {
   res.send(`${animal} says: '${sound[animal]}'`)
  } else if (animal === 'cat') {
    res.send(`${animal} says: '${sound[animal]}'`)
  } else if (animal === 'cow') {
    res.send(`${animal} says: '${sound[animal]}'`)
  } else {
   res.send('we did not cover this animal')
  }
})