higunjan higunjan - 4 months ago 14
Javascript Question

Javascript ORing in variable how it works?

I want to know the process of ORing in javascript variable. I used below code for just testing purpose. I want just know the process behind these ORing in var. I know the process when we are using in if condition. Please any one explain me in details.

var a = a || "2010" || "Gunjan" || 20;
console.log(a);
//output 2010


When I console var
a
then it gives me output like
2010
.


  1. Why?

  2. How?

  3. Can anyone one explain me background process?


Answer

The Logical Operators returns the value of one of the operands, so if the operands returns a non boolean value then the logical operation could return a non boolean value

Logical operators are typically used with Boolean (logical) values. When they are, they return a Boolean value. However, the && and || operators actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they may return a non-Boolean value.

Also looking at Short-Circuit Evaluation, the OR operator will stop executing of further conditions once one of the operands is true.

Now looking at your condition var a = a || "2010" || "Gunjan" || 20;, since you have used var a, I'm assuming you are declaring the variable a here, so when the RHS is executed a has a value undefined which is falsy so the OR operator executes the second operand which is a string literal 2010 which is a non boolean but truthy value so that is returned as a result of this operations