Why doesn’t my equality comparison using = (a single equals) work correctly? [duplicate]

= is always assignment. Equality comparison is == (loose, coerces types to try to make a match) or === (no type coercion).

So you want

if (str === ''){
// -----^^^

not

// NOT THIS
if (str=""){
// -----^

What happens when you do if (str="") is that the assignment str="" is done, and then the resulting value ('') is tested, effectively like this (if we ignore a couple of details):

str="";
if (str) {

Since '' is a falsy value in JavaScript, that check will be false and it goes to the else if (str.length <= 9) step. Since at that point, str.length is 0, that’s the path the code takes.

Leave a Comment