Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

it's weird that the switch condition in javascript

I find that these two below are equivalent, but is quit weird that, single = is not a relation operator but an assignment operator, why it works in the second one?

First:

switch (true) 
  {
    case color == 'green':case color == 'red':case color == 'blue':case color == 'pink':
      alert('colorful')
      break;
    case color == 'black':case color == 'white':
      alert('classical')
      break;
    default:
      alert('dull')
      break;              
  }

Second:

switch (color) 
  {
    case color = 'green':case color = 'red':case color = 'blue':case color = 'pink':
      alert('colorful')
      break;
    case color = 'black':case color = 'white':
      alert('classical')
      break;
    default:
      alert('dull')
      break;              
  }
like image 587
Rupert Avatar asked Jan 22 '14 14:01

Rupert


1 Answers

At the first switch statement your checking for boolean value. So the valid results will be either true or false.

For the second switch statement we're searching for a color. The result of assignment is the assignment value it self.

color = 'green' will return green and will be exactly like writing case 'green': except that it will also change the value of color. BUT and it's a big but, you are changing the value of color while checking what the color and that may cause big side effects.

You better use the correct formal style for case 'green': and not other variations. Especially not assignment variations.

like image 75
Orel Eraki Avatar answered Oct 11 '22 13:10

Orel Eraki