Skip to content Skip to sidebar Skip to footer

How To Write OR In Javascript?

How do you write OR in Javascript? Example : if ( age **or** name == null ){ do something }

Solution 1:

Simply use:

if ( age == null || name == null ){    
    // do something    
}

Although, if you're simply testing to see if the variables have a value (and so are 'falsey' rather than equal to null) you could use instead:

if ( !age || !name ){    
    // do something    
}

References:


Solution 2:

if (age == null || name == null) {

}

Note: You may want to see this thread, Why is null an object and what's the difference between null and undefined?, for information on null/undefined variables in JS.


Solution 3:

The problem you are having is the way that or associates. (age or name == null) will actually be ((age or name) == null), which is not what you want to say. You want ((age == null) or (name == null)). When in doubt, insert parentheses. If you put in parentheses and evaluated, you would have seen that the situations became something like (true == null) and (false == null).


Solution 4:

We don't have OR operator in JavaScript, we use || instead, in your case do...:

if (age || name == null) {
  //do something
}

Post a Comment for "How To Write OR In Javascript?"