0
if executes statement even if variable values arent equal?
var x = 5 var y = 10 if(x=y){ alert("X is equal to Y") } even if variables X and Y aren't equal, the alert pops up. why is this the case? I know about the "==" and "===" sign and the alert doesn't execute when using this but how come with the "="? I just want to know why
3 Answers
+ 3
Maybe it's because the type coercion. It only compares the types of x and y => both of them numbers so it's true. You should change it to "===" which means identical.
+ 1
// Assign y value to x.
x = y
// x === 10: true.
You used assignment. This is neither abstract comparision == nor strict comparision ===. The statement is executed if the condition is truthy. x is now 10, and any number except 0 is truthy. Thus alert is called.
0
Dâœâœâœâœ7âŁ7âŁ7⣠both == and === compare the type and value of 2 operands, but == tries to find the 'closest' type to match the operand while === doesn't.