Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does javascript logical assignment work?

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?

like image 430
Incognito Avatar asked Dec 15 '10 03:12

Incognito


People also ask

How does assignment work in JavaScript?

Assignment (=)The simple assignment operator ( = ) is used to assign a value to a variable. The assignment operation evaluates to the assigned value. Chaining the assignment operator is possible in order to assign a single value to multiple variables.

How does JavaScript evaluate &&?

Description. Logical AND ( && ) evaluates operands from left to right, returning immediately with the value of the first falsy operand it encounters; if all values are truthy, the value of the last operand is returned.

What is logical AND assignment operator?

The ||= operator The ||= is pronounced as “Logical OR assignment operator” and is used in between two values. If the first value is falsy, then the second value is assigned. It is evaluated left to right.

What are the 3 logical operators in JavaScript?

Logic operators are used to find the logic between variables in JavaScript. There are three logical operators in JavaScript: || (OR), && (AND), ! (NOT).


2 Answers

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';

like image 124
dheerosaur Avatar answered Oct 19 '22 23:10

dheerosaur


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".

like image 36
Anon. Avatar answered Oct 19 '22 23:10

Anon.