tags:

views:

169

answers:

6

In Javascript, what does it mean when there is a logical operator in a variable declaration? example:

var z = x || y;

Thanks!

A: 

It means z will be a Boolean object containing the evaluation of "X || y"

Khanser
No, it won't. See other answers.
David Dorward
+1  A: 

It means that if x is set, the value for z will be x, otherwise if y is set then its value will be set as the z's value.

it's the same as

if(x)
  z = x;
else
  z = y;

It's possible because logical operators in JavaScript doesn't return boolean values but the value of the last element needed to complete the operation (in an OR sentence it would be the first non-false value, in an AND sentence it would be the last one). If the operation fails, then false is returned.

Andris
this is wrong! if (x) { z = x; } else {z = y;} if the first value is false, the second value is always assigned not depending what the value actually is.
evilpie
Except that I think it just assigns y to z if x is *false*. That's the way it works for me in FF, of course, that might be implementation dependent, too.
tvanfosson
The last part about returning false isn't true (no pun intended). If the first value is falsey, the `||` operator just returns the second value, regardless of whether it's truthy or not.
Matthew Crumley
-1. Your equivalent code snippet is accurate, but the important point is that `z` gets set to the value of `x` if that value is *truthy*. Otherwise it gets set to the value of `y`. This means that if `x` is set to, for example, `0`, or the empty string `""`, this doesn’t do what you say, since those values are *falsy*.
Daniel Cassidy
+9  A: 

This is made to assign a default value, in this case the value of y, if the x variable is falsy.

The boolean operators in JavaScript can return an operand, and not always a boolean result as in other languages.

The Logical OR operator (||) returns the value of its second operand, if the first one is falsy, otherwise the value of the first operand is returned.

For example:

"foo" || "bar"; // returns "foo"
false || "bar"; // returns "bar"

Falsy values are those who coerce to false when used in boolean context, and they are 0, null, undefined, an empty string, NaN and of course false.

CMS
+1 Is there another operator like that? Or is `||` exclusive.
OscarRyz
CMS
Thank you, really appreciate your help.
anthonypliu
*Falsy* is in fact the technical term.
ChaosPandion
@anthonypliu: You're welcome, glad to help!
CMS
A: 

It will evaluate X and, if X is not null, the empty string, or 0 (logical false), then it will assign it to z. If X is null, the empty string, or 0 (logical false), then it will assign y to z.

var x = '';
var y = 'bob';
var z = x || y;
alert(z);

Will output 'bob';

tvanfosson
You should clarify what you mean by ‘empty’. Empty strings coerce to `false`, but empty arrays or objects coerce to `true`.
Daniel Cassidy
@Daniel "null, empty, or 0" -- null would apply with respect to arrays and objects. Point taken, though.
tvanfosson
+1  A: 

It's setting the new variable (z) to either the value of x if it's "truthy" (non-zero, a valid object/array/function/whatever it is) or y otherwise. It's a relatively common way of providing a default value in case x doesn't exist.

For example, if you have a function that takes an optional callback parameter, you could provide a default callback that doesn't do anything:

function doSomething(data, callback) {
    callback = callback || function() {};
    // do stuff with data
    callback(); // callback will always exist
}
Matthew Crumley
+2  A: 

Javacript uses short-circuit evaluation for logical operators || and &&. However, it's different to other languages in that it returns the result of the last value that halted the execution, instead of a true, or false value.

The following values are considered falsy in JavaScript.

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

Ignoring the operator precedence rules, and keeping things simple, the following examples show which value halted the evaluation, and gets returned as a result.

false || null || "" || 0 || NaN || "Hello" || undefined // "Hello"

The first 5 values upto NaN are falsy so they are all evaluated from left to right, until it meets the first truthy value - "Hello" which makes the entire expression true, so anything further up will not be evaluated, and "Hello" gets returned as a result of the expression. Similarly, in this case:

1 && [] && {} && true && "World" && null && 2010 // null

The first 5 values are all truthy and get evaluated until it meets the first falsy value (null) which makes the expression false, so 2010 isn't evaluated anymore, and null gets returned as a result of the expression.

The example you've given is making use of this property of JavaScript to perform an assignment. It can be used anywhere where you need to get the first truthy or falsy value among a set of values. This code below will assign the value "Hello" to b as it makes it easier to assign a default value, instead of doing if-else checks.

var a = false;
var b = a || "Hello";

You could call the below example an exploitation of this feature, and I believe it makes code harder to read.

var messages = 0;
var newMessagesText = "You have " + messages + " messages.";
var noNewMessagesText = "Sorry, you have no new messages.";
alert((messages && newMessagesText) || noNewMessagesText);

Inside the alert, we check if messages is falsy, and if yes, then evaluate and return noNewMessagesText, otherwise evaluate and return newMessagesText. Since it's falsy in this example, we halt at noNewMessagesText and alert "Sorry, you have no new messages.".

Anurag