The OR Operator (JS Demystified) | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 10

The OR Operator (JS Demystified)

Classical Meaning: alert(true || true) // true alert(true || false) // true alert(false || true) // true alert(false || false) // false JS Quirks: 1. Reads from Left to Right 2. Convert Operand to Boolean (any value type) 3. Returns the First Truthy (original value) 4. Returns last value if all operands are falsy. Examples: alert(1 || 0) // 1 alert(1 || 2 || 3) // 1 (corrected) alert(alert(1) || 2) // 2 alert(0 || null || undefined) // undefined

28th Apr 2017, 9:35 PM
Benneth Yankey
Benneth Yankey - avatar
7 Answers
+ 9
0 is false, everything else is true. null is nothing.
28th Apr 2017, 10:14 PM
Emore Anzolin
Emore Anzolin - avatar
+ 9
This is called lazy short-circuit evaluation*. first_one_that_is_true = a || b || c || d; first_one_that_is_false = e && f && g && h; Behavior notes: alert(1 || 2 || 3) actually returns 1. (edit: fixed) alert(alert() || ...) returns the next value because alert itself returns 'undefined' (this evaluates as false). (edit:example changed; left for visitor info) * Often used to set default values, people will put one final 'guaranteed' truthy/falsy at the end to check for a default condition.
29th Apr 2017, 12:39 AM
Kirk Schafer
Kirk Schafer - avatar
+ 3
Thanks @Kirk was a typo mistake....👍
29th Apr 2017, 4:09 AM
Benneth Yankey
Benneth Yankey - avatar
+ 1
Hi @America Perez
6th Aug 2017, 9:16 PM
Benneth Yankey
Benneth Yankey - avatar
+ 1
What was the reason of changing "alert()" to "alert(1)" if both return undefined?
6th Aug 2017, 9:26 PM
Andrew Harchenko (Tomsk)
Andrew Harchenko (Tomsk) - avatar
+ 1
0 has it rough with boolean operators same behavior is in Py
7th Aug 2017, 1:50 AM
Goran B
Goran B - avatar
0
Hello
6th Aug 2017, 9:14 PM
America Perez
America Perez - avatar