-5

How do you write OR in Javascript?

Example :

if ( age **or** name == null ){
    do something
}
Zoltan Toth
  • 46,981
  • 12
  • 120
  • 134
Dany
  • 461
  • 4
  • 7
  • 12

4 Answers4

16

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:

David Thomas
  • 249,100
  • 51
  • 377
  • 410
10
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.

Community
  • 1
  • 1
user1103976
  • 539
  • 3
  • 11
  • `===` would be a smidge better – Matt Greer Sep 04 '12 at 14:56
  • Don´t just check for a null variable, it could be undefined also. See http://stackoverflow.com/questions/2559318/how-to-check-for-undefined-or-null-variable-in-javascript – pdjota Sep 04 '12 at 14:59
  • @pdjota `undefined == null` is true; you only need to differentiate if you're using `===` or specifically care about the difference. – Dave Newton Sep 04 '12 at 15:36
0

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

Paul Fleming
  • 24,238
  • 8
  • 76
  • 113
Stephen Garle
  • 299
  • 1
  • 5
0

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

if (age || name == null) {
  //do something
}
Alireza
  • 100,211
  • 27
  • 269
  • 172