Need a little help at JS. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Need a little help at JS.

In my this code... switch(true) {case (I=0): var Oyp=7; case(I>0)&&(I<70000): var Oyp =6; case(I>=70000)&&(I<200000): var Oyp=5; case(I>=200000)&&(I<500000): var Oyp =4; case(I>=500000)&&(I<900000): var Oyp=3; case(I>=900000)&&(I<1356000): var Oyp=2; case(I>=1356000)&&(I<1761000): var Oyp=1; } document.write (Oyp); Suppose the value of I is 345180, still the value of Oyp will be printed as undefined. Why? Thanks for answering.

1st Oct 2017, 5:04 PM
Isair Calhawk
Isair Calhawk - avatar
5 Answers
+ 9
You cant use condition in switch
1st Oct 2017, 6:11 PM
Mahdi Momeni
Mahdi Momeni - avatar
+ 3
Exactly: you can use condition expression in 'case' statement, but the 'switch' expression value will be compared to the value of each 'case' expression... Typically, switch-case statements are use to compare a single variable value to only once value at each case: switch (myvar) { case value: // do something if myvar == value // and run each next case block // until a 'break' keyword occurs // most of the time, each case block will end with it // in all cases, no more 'case' statement will be tested case result_of_expression: // do something if myvar == result of expression // as a condition is an expression, you can use one, but your 'myvar' will be compared necessarly to boolean value true or false } So, in your code, at first case statement, condition of nexted instruction execution is equivalent to: if (true == (l=0)) ... wich is false (and where you probably do a first mistake: you doesn't compared l to 0, but assign 0 to l... so the 'result' of the assignement-expression is the value of l, and 0 is not equivalent to true -- and almost, l is now equal to zero for next 'case' statements ;P). Anyway, if l is already equal to 0, the 'case' statement will always be false ^^ And if by magical it would be true, all different case block will be running, as you don't use 'break' keyword... The second 'case' statement could be writen: if (true == ((l>=0)&&(l<70000)) ... which is actually always true, as l is now equal to zero ^^ So Oyp is set to 6, but next to 5, then 4... and finally will carrying 1 at last 'case' block... if Oyp is declared outside the 'switch' scope (closure), else Oyp is unknown (undefined) after exiting the 'switch' closure ;)
1st Oct 2017, 11:41 PM
visph
visph - avatar
+ 1
you have to define oyp outside the switch scope
1st Oct 2017, 5:12 PM
Chrizzhigh
Chrizzhigh - avatar
+ 1
Okay thanks chrizzhigh
1st Oct 2017, 5:13 PM
Isair Calhawk
Isair Calhawk - avatar
0
can you mark it as answer ^^ and no probs keep on coding
1st Oct 2017, 5:14 PM
Chrizzhigh
Chrizzhigh - avatar