javascript - statement - ternary operator




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

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?


In the case of if hrs-12 evaluates to 0, the person wants hrs to be assigned 12 since 0 is not suitable.

Since 0 evaluates to false, the expression becomes false || 12, in which case 12 would be chosen since it's truthy.


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


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.





javascript