&& - Javascript Shorthand-What Does the '||' Operator Mean When Used in an Assignment?

es6 if (6)

This question already has an answer here:

I just took a look at this answer, and I noticed the following line of javascript code:

hrs = (hrs - 12) || 12;

My Question:

What does the '||' operator mean when used in an assignment?


It always means the same: logical OR

It's a common trick that makes use of type casting. Many non-boolean expressions evaluate to false. It's the same as this:

hrs = (hrs-12)
    hrs = 12;

And the if() works because 0 casts to false. It's also used to deal with undefined variables:

function foo(optionalValue){
    var data = optionalValue || "Default value";
foo("My value");

It means "If the first half of the expression is false, then use the second half instead."

Practically in this example, it means that hrs will be set to hours-12, unless hours-12 is zero, in which case it will hrs will be set to 12.

In this case, the code assigns 12 to hrs if hrs-12 = 0 (as JavaScript sees it, 0 = false).

More generally, it assigns the latter value to the variable if the former value evaluates to 0, the empty string, null, undefined, etc.

It means if hrs - 12 is evaluated to false (false, null, undefined, NaN, '', 0), then 12 will be assigned to hrs.

It means "short circuit or". I.e. if the first part of the expression is false use the second instead. Wikipedia has an article on this with syntax for a number of languages.

After reading this thread, I feel confused with JavaScript Prototype Chain, then I found these charts


it's a clear chart to show JavaScript Inheritance by Prototype Chain



this one contains a example with code and several nice diagrams.

prototype chain ultimately falls back to Object.prototype.

prototype chain can be technically extended as long as you want, each time by setting the prototype of the subclass equal to an object of the parent class.

Hope it's also helpful for you to understand JavaScript Prototype Chain.