6

Javascript code:

var a = (b) ? b : 40;

It is working, just NetBeans says: "Use the || operator (Column [where the ? is])". I didn't find any explanation.

What is it?

Thanks!

Gábor Varga
  • 840
  • 5
  • 15
  • 25

2 Answers2

6

If you are just testing for the truthyness of b then you can do this:

var a = b || 40;

… which is shorter and (arguably) more obvious. In JavaScript, || is a short circuit operator. It returns the left hand side if it is true, otherwise it returns the right hand side. (i.e. it doesn't return a boolean unless the input was a boolean).

If you want to see if b is actually defined, then you are better off with:

var a = (typeof b !== "undefined") ? b : 40;
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
3

The pipes are the or statement. var a = b || 40 says if b is non-falsey value, let a=b, otherwise 40.

Snuffleupagus
  • 6,365
  • 3
  • 26
  • 36