Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use the || operator notice

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!

like image 621
Gábor Varga Avatar asked May 22 '12 15:05

Gábor Varga


People also ask

What is|| operator in JavaScript?

The logical OR ( || ) operator (logical disjunction) for a set of operands is true if and only if one or more of its operands is true. It is typically used with boolean (logical) values. When it is, it returns a Boolean value.

What does this mean |=?

The bitwise OR assignment operator ( |= ) uses the binary representation of both operands, does a bitwise OR operation on them and assigns the result to the variable.

What does '!' Mean in JavaScript?

The ! symbol is used to indicate whether the expression defined is false or not. For example, !( 5==4) would return true , since 5 is not equal to 4. The equivalent in English would be not .

What does {} mean in JavaScript?

So, what is the meaning of {} in JavaScript? In JavaScript, we use {} braces for creating an empty object. You can think of this as the basis for other object types. Object provides the last link in the prototype chain that can be used by all other objects, such as an Array.


2 Answers

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;
like image 64
Quentin Avatar answered Oct 02 '22 04:10

Quentin


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

like image 27
Snuffleupagus Avatar answered Oct 02 '22 04:10

Snuffleupagus