+16

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!

4/10/2019 4:44:08 PM

Ahad

6 Answers

New Answer

+14

M. Watney HonFu Thank you man. I was forget that.

+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.

+5

+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)

+2

Use bitwise operators ....

+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.