Logical operators javascript

Asked

Viewed 1,112 times

4

I have a question

Because this operation doesn’t work?

if ($(v).attr('jgForm-required') || $(v).attr('jgForm-email') && $(v).is(":visible")) {
......................
}

And that works? What’s the difference?

if ($(v).attr('jgForm-required') || $(v).attr('jgForm-email')) {
    if($(v).is(":visible")){
    ...............................
    }
}

EXAMPLE

  • You can create a demo(jsFiddle) for this case ?

  • Not knowing what it is v and the attributes, it gets a little complicated to explain... Could show us what is the variable v?

1 answer

6


The operator and (&&) has greater precedence than the or (||). That means that in a sequence of ands and Ors, the ands are resolved before. Therefore the first version is interpreted as:

X || (Y && Z)

You can force the interpretation you want using parentheses:

(X || Y) && Z

That is to say:

if ( ($(v).attr('jgForm-required') || $(v).attr('jgForm-email')) && $(v).is(":visible")) {
    // ...
}
  • That’s right! Thank you very much for the explanation!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.