JS Comparison give unexpected result, why? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 18

JS Comparison give unexpected result, why?

var x = 5; var y = 8; if (x>y){ document.write(x-y); } else if (x=y){ document.write(x+y); } else{ document.write(x*y); } // 16 Why 16? it will be 40!

10th Apr 2019, 4:44 PM
Ahad
Ahad - avatar
6 Answers
+ 16
M. Watney HonFu Thank you man. I was forget that.
10th Apr 2019, 5:01 PM
Ahad
Ahad - avatar
+ 9
Replace = with == inside else if condition. Its actually assigning the value of y to the x, that's is, now x=8, also y=8 hence x+y=16.
10th Apr 2019, 4:56 PM
Шащи Ранжан
Шащи Ранжан - avatar
+ 5
else if (x==y)!
10th Apr 2019, 4:57 PM
HonFu
HonFu - avatar
+ 3
Use bitwise operators ....
12th Apr 2019, 6:40 AM
Sanjay Kamath
Sanjay Kamath - avatar
+ 2
var x = 5; var y = 8; if (x>y){ document.write(x-y); } else if (x===y){ document.write(x+y); } else{ document.write(x*y); } // not (x = y ) instead ( x === y)
11th Apr 2019, 9:16 AM
Programming For All
Programming For All - avatar
+ 1
= is for assigning variables, and == or === is to compare. == is equal but not strict to any specific type, while === is strict to the same types on both operands. In your case where you do, ... if(x = y) { document.write(x+y); } ... You first assign the variable y which is 8 to x which previously was 5 but is now overwritten with 8. There it writing 16 to the document. document.write(x+y) is essentially document.write(8+8) in that case. And second of all, assigning in an if statement, most likely always return true thus that if statement being executed. Hope this was a pretty detailed explanation on what went code wrong cuz you accidently assigned instead of compared two values.
13th Apr 2019, 8:50 PM
Ragey
Ragey - avatar