Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing an Object to Switch Case Javascript

Tags:

javascript

I wanted to have a switch/case statement that accepts an object in Javascript.

The function looks like this.

const validate = (values) => { values is an object, can be accessed like so (values.bar, values.foo)
  const errors = {}

  switch(values) {
    case !values.bar || values.bar === '':
       errors.bar = 'Enter bar'
    case values.bar.length < 10: 
       errors.bar = 'Bar is too short'
    case !values.foo || values.foo === '':
       errors.foo = 'Enter foo'
    ...

    default: 
      return errors
  } 
}

This doesn't work and I have used an if/else statement instead, but I feel like a switch/case would be perfect for this kind of example. Thoughts?

like image 733
Diego Avatar asked Apr 25 '16 15:04

Diego


1 Answers

Change

switch(values) {

To

switch(true) {

switch checks with strict equality.

And use, if necessary some break if you do not want to fall through the switch cases (kudos to blex).

like image 141
Nina Scholz Avatar answered Oct 01 '22 13:10

Nina Scholz