0

I have the following code:

console.log(usernameExists);
if (usernameExists = true) {
  console.log("returning true");
  return true;
} else if (looped = true) {
  console.log(usernameExists+" is returned");
  looped = null;
  return false;
}

The first console.log(usernameExists) is returning false, but still I am getting a console message of "returning true", and the function in which this is, is returning true! I simply can't figure this out.

Cœur
  • 37,241
  • 25
  • 195
  • 267
aravk33
  • 469
  • 2
  • 10
  • 18

4 Answers4

1

= is an assignment, so you're setting the variable to true, which itself makes the if statement true. What you want is to check if the variable is set to true. In order to do that, use the == or === operators.

Constantin Groß
  • 10,719
  • 4
  • 24
  • 50
1

The condition is always true, because you assign this value to the variable and this is the value which is evaluated for the if clause.

But you could use a direct check without a compare value (and without assigning this value).

Beside that, you could change the else part to only an if part, becaue you exit the function with return, so no more else happen in this case.

if (usernameExists) {
    console.log("returning true");
    return true;
}
if (looped) {
    console.log(usernameExists+" is returned");
    looped = null;
    return false;
}
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • 1
    I didn't downvote, however: The answer does not really explain the initial problem. That's not what's bugging me tough, but leaving in the wrong code just commented out - I'd rather not leave that in the answer. – Constantin Groß Nov 01 '17 at 10:55
0

For checking conditions, you need to use '==' operator. '=' means assignment operator. Whereas a '===' checks for value and type. Hope that is the issue.

Franklin Pious
  • 3,670
  • 3
  • 26
  • 30
0

In your conditions you are using a single equal!!! Therefore, it is a assignation operation that is done instead of comparison! So you are not checking that your variable is equal to true but you are assigning it to true and since your assignement operation was successful your condition is at the same time fulfilled.

Change it with two or tree equals == or === instead of =

Usage and differences between == and === are explained very well here:

Which equals operator (== vs ===) should be used in JavaScript comparisons?

Koby Douek
  • 16,156
  • 19
  • 74
  • 103
Allan
  • 12,117
  • 3
  • 27
  • 51