Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript || or operator with an undefined variable

Tags:

javascript

I have been doing some reading lately one article I read was from Opera.

http://dev.opera.com/articles/view/javascript-best-practices/

In that article they write this:

Another common situation in JavaScript is providing a preset value for a variable if it is not defined, like so:

if(v){   var x = v; } else {   var x = 10; } 

The shortcut notation for this is the double pipe character:

var x = v || 10; 

For some reason, I can't get this to work for me. Is it really possible to check to see if v is defined, if not x = 10?

--Thanks. Bryan

like image 856
bryan sammon Avatar asked Jan 02 '11 02:01

bryan sammon


People also ask

What is the || 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 is || in JavaScript variable declaration?

Well, it's my understanding that || is going to be that Boolean "or," so this is going be "set current to either the variable called newGallery or zero," I believe!

What does || mean inside a JavaScript function?

The Logical OR operator ( || ) is an operator that returns its first or second operand depending on whether the first is truthy.

Is null == undefined?

It means null is equal to undefined but not identical. When we define a variable to undefined then we are trying to convey that the variable does not exist . When we define a variable to null then we are trying to convey that the variable is empty.


1 Answers

That Opera article gives a poor description of what is happening.

While it is true that x will get the value of 10 if v is undefined. It is also true that x will be 10 if v has any "falsey" value.

The "falsey" values in javascript are:

  • 0
  • null
  • undefined
  • NaN
  • "" (empty string)
  • false

So you can see that there are many cases in which x will be set to 10 besides just undefined.

Here's some documentation detailing the logical operators. (This one is the "logical OR".) It gives several examples of its usage for such an assignment.

Quick example: http://jsfiddle.net/V76W6/

var v = 0;  var x = v || 10;  alert( x ); // alerts 10 

Assign v any of the falsey values that I indicated above, and you'll get the same result.

like image 149
user113716 Avatar answered Oct 11 '22 13:10

user113716