Can't make multiple if conditions in JavaScript?

930 Views Asked by At

I have absolutely no idea why this is not working. Makes no sense to me.

This returns a "syntax error: parse error":

if ($(this).attr("id") === 'search' || opening = true) return false;

For good measure, I also tried the following, which yielded the same result:

if (1 = 1 && 2 = 2) { return false; }
6

There are 6 best solutions below

1
jtbandes On BEST ANSWER

There are three different operators at play:

  • =: assignment
  • ==: equality
  • ===: strict equality

= actually modifies a variable, so you shouldn't use it inside if statements. That is, you should use ... || opening == true) instead of ... || opening = true).

1
Jeremy On

In JavaScript = is used to assign values, while == and === are used to compare them.

When you put opening = true in your if statement, you aren't checking if opening is true, you are setting opening to true. Try using == instead.

For example,

var x = 5;
if (x == 10) {
    alert("x is 10");
} else {
    alert("x isn't 10");
}

will display "x isn't 10", while

var x = 5;
if (x = 10) {
    alert("x is 10");
} else {
    alert("x isn't 10");
}

will display "x is 10".

0
Ibu On

You have an error in your condition

if ($(this).attr("id") === 'search' || opening = true) return false;

should be

if ($(this).attr("id") === 'search' || opening == true) return false;

the problem is with the equals sign

= is different to ==

the first one is the assignment operator. the second one is for comparison

0
Pablo Fernandez On

the first example should read:

if ($(this).attr("id") === 'search' || opening == true) return false;

and the second:

if (1 == 1 && 2 == 2) { return false; }

Note the double equals (==) sign for logic equals is not the same as the single equals (=) sign, that handles variable assignment.

0
Brad On

When you test like this:

opening=true;

What you are really doing is setting opening to the value of true. Use == instead.

Finally, order of operations, even if correct, can get confusing. Put parenthesis around each part of the comparison.

if (($(this).attr("id") === 'search') || (opening == true)) return false;
1
Stephane Paquet On

My guess is that === does not exist. == is for testing equality

so if ($(this).attr("id") === 'search' || opening == true) return false; should be if ($(this).attr("id") == 'search' || opening == true) return false;