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

I'm trying to check if a string is blank, less than or equal to 9 digits, or up to 10 digits. But it always follows the else if (str.length <= 9).

if (str = ''){
    console.log("The string cannot be blank");
} else if (str.length <= 9) {
    console.log("The string must be at least 9 characters long");
} else if (str.length <= 10) {
    console.log("The string is long enough.");
}

No matter what I put in, I always get The string must be at least 9 characters long. Why?


Solution 1:

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