0

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?

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Sam
  • 39
  • 5
  • 2
    I'm sure there must be a canonical question for this... – T.J. Crowder Jul 08 '16 at 13:50
  • 1
    @T.J.Crowder — Possibly, but I'd be surprised if any of them had a title as clear as this one. Mostly they come to do "My code doesn't work and I don't know why" – Quentin Jul 08 '16 at 13:54
  • @Quentin: Yeah. I'm editing this into one. :-) – T.J. Crowder Jul 08 '16 at 13:54
  • @T.J.Crowder — Ooops, didn't notice that was your edit :) – Quentin Jul 08 '16 at 13:55
  • @Quentin: No worries, that's a better title – T.J. Crowder Jul 08 '16 at 13:57
  • There's [this](http://stackoverflow.com/questions/3791287/a-single-equals-in-an-if-javascript-any-good-reason) and [this](http://stackoverflow.com/questions/17974377/how-does-the-single-equal-sign-work-in-the-if-statement-in-javascript) which are similar. – gcampbell Jul 08 '16 at 13:59
  • @ Sam: Your original question also did this: `if (jQuery('phone_number').length)`, which is incorrect for an unrelated reason: That's telling jQuery to look up all elements with the tag name `phone_number`. I suspect you probably meant `jQuery.trim(phone_number).length`. – T.J. Crowder Jul 08 '16 at 14:01

1 Answers1

7

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

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875