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

29th Aug 2018, 7:51 AM
Joao Jose
Joao Jose - avatar
3 odpowiedzi
+ 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.
29th Aug 2018, 8:02 AM
TheWh¡teCat 🇧🇬
TheWh¡teCat 🇧🇬 - avatar
+ 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.
29th Aug 2018, 8:44 AM
Hoàng Nguyễn Văn
Hoàng Nguyễn Văn - avatar
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.
29th Aug 2018, 8:57 AM
Hoàng Nguyễn Văn
Hoàng Nguyễn Văn - avatar