18

In javascript, if we have some code such as

var a = "one";
var b = q || a;
alert (b);

The logical OR operator will assign a's value to b, and the alert will be "one."

Is this limited to assignments only or can we use it everywhere?

It seems an empty string is treated the same as undefined. Is this right?

How does this work with AND variables? What about combinations of them?

What is a good example of when to use these idioms, or when not to?

Incognito
  • 20,537
  • 15
  • 80
  • 120
  • 1
    See [JavaScript OR (||) variable assignment explanation ](http://stackoverflow.com/questions/2100758/javascript-or-variable-assignment-explanation) and [In Javascript, what does it mean when there is a logical operator in a variable declaration? ](http://stackoverflow.com/questions/3088098/in-javascript-what-does-it-mean-when-there-is-a-logical-operator-in-a-variable-d). – Matthew Flaschen Dec 15 '10 at 03:40
  • 1
    Don't use it. It is stupid syntactic construct that is not intuitive and slows a lot of people down when reading code. – MK. Dec 15 '10 at 03:51
  • 6
    @MK, don't rule out a common construct just because people that don't (yet) know JavaScript are unfamiliar with it. – Matthew Flaschen Dec 15 '10 at 04:03
  • @Matthew Didn't see those questions, I'm voting to close. – Incognito Dec 15 '10 at 13:08

6 Answers6

27

For your q || a to evaluate to a, q should be a 'falsy' value. What you did is called "Short circuit evaluation".

Answering your questions:

  1. The logical operators (like and - &&, or - ||) can be used in other situations too. More generally in conditional statements like if. More here

  2. Empty string is not treated as undefined. Both are falsy values. There are a few more falsy values. More here

  3. AND, or && in JavaScript, is not a variable. It is an operator

  4. The idiom you have used is quite common.

    var x = val || 'default'; //is generally a replacement for

    var x = val ? val : 'default' //or

    if (val) var x = val; else var x = 'default';

dheerosaur
  • 14,736
  • 6
  • 30
  • 31
9

The way || works in Javascript is:

  1. If the left operand evaluates as true, return the left operand
  2. Otherwise, return the right operand

&& works similarly.

You can make use of this for in-line existence checks, for example:

var foo = (obj && obj.property)

will set foo to obj.property if obj is defined and "truthy".

silvo
  • 4,011
  • 22
  • 26
Anon.
  • 58,739
  • 8
  • 81
  • 86
1

This behavior is shared with other scripting languages like Perl. The logical OR operator can be used as a syntactic shorthand for specifying default values due to the fact that the logical OR operator stops evaluating its operands when it encounters the first expression that evaluates to true: "evaluate the first operand and if the value is interpreted as not false, assign it. Otherwise repeat for the second operand."

I find I often use this behavior to specify default values for function parameters. E.g.

function myFunction(foo, bar) {
    var fooValue = foo || "a";

    // no need to test fooValue -- it's guaranteed to be defined at this point
}
Kim Burgaard
  • 3,508
  • 18
  • 11
  • What if the value of foo is false (not "false")? – JVM Mar 27 '17 at 20:46
  • That will result in fooValue == "a". In a boolean context false, null, undefined, 0, NaN and the empty string all evaluate to false -- see https://developer.mozilla.org/en-US/docs/Glossary/Falsy for details – Kim Burgaard Mar 27 '17 at 22:56
  • Correct. Then, this might fail at the place where one actually needs false as a value. – JVM Mar 28 '17 at 01:29
  • In those case you can check for foo == null (which evaluates to true if foo is either null or undefined) or explicitly for foo === undefined to allow falsy values to be specified as arguments. The question was specifically what logical assignments with a right-hand side like a || b does and that's what I answered above. – Kim Burgaard Mar 28 '17 at 16:17
1

I'm not quite sure I follow your question. You can use an expression anywhere you can use an expression, and a logical operator on two expressions results in an expression.

alert(q||a);
alert(true||false);

var x=5;
var y=0;
if (y!=0 && x/y>2) { /*do something*/ }

The last bit is useful. Like most languages, Javascript 'short-circuits' ANDs and ORs. If the first part of an AND is false, it doesn't evaluate the second bit - saving you a divide-by-0. If the first part of an OR is true, it doesn't evaluate the second.

But you can use boolean operators anywhere you can use an expression.

Robert
  • 6,412
  • 3
  • 24
  • 26
1

Javascript evaluates logic by truethness/falseness. Values such as (false, "", null, undefined, 0, -0) are evaluated as logic false.

Combine this with the lazy evaluation, 'OR' operations are now evaluated from left to right and stops once true is found. Since, in your example, the truthness is not literally a boolean, the value is returned.

In this case:

x = 0; y = 5; alert(y || x)/*returns 5*/;  alert(x || y)/*also returns 5*/;

this can also be other objects.

functionThatReturnsTrue() || functionThatDoesSomething();
gianebao
  • 17,718
  • 3
  • 31
  • 40
1

IMHO - don't use for boolean type assignment. It can be confusing. As undefined !== false, ie false itself is a value.

E.g. If u want to copy a field value from an object if and only if that field is defined

var bar.value = false;
var foo = true;

var foo = bar.value || foo;  // ==> should be false as bar.value is defined

For boolean type assignment, u should really use

var foo = (bar.value !== undefined) ? bar.value : foo;
Joe Kuan
  • 119
  • 1
  • 3