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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With