Problem Description
Let's practice using the binary Logical OR || to provide a "fallback" value. This is its most common use case for this operator.
Write a function greet(name) that takes a single name string as an argument.
If a
nameis provided (e.g.,"Alice"), it should return"Hello, Alice!".If the
nameis not provided (it will beundefined) or if it's an empty string (""), it should return"Hello, Guest!".
Constraint: You cannot use an if statement for this.
Test Cases:
greet("Alice")should return"Hello, Alice!"greet("")should return"Hello, Guest!"greet(undefined)should return"Hello, Guest!"
馃挕 The 'Syntax Nudge'
This is the perfect place to use the Logical OR (||) operator.
Remember its core rule: valueA || valueB The JavaScript engine first looks at valueA.
If
valueAis "truthy" (any string with content, any number not 0,true, objects, arrays), it just returnsvalueAand stops.If
valueAis "falsy" (specificallyundefined,null,""(empty string),0,false,NaN), it discards it and returnsvalueBinstead.
We can think of operators in terms of how many "things" (we call them operands) they work on.
Unary Operator: Works on one thing.
!(Logical NOT):!isReady(flipsisReadyfrom true to false)typeof:typeof 10(tells you the type is "number")i++(Increment): Works on the single variablei.
Binary Operator: Works on two things. This is most of what you use every day.
1 + 2(The+works on1and2)x > y(The>works onxandy)a && b(Logical AND)a || b(Logical OR - the one that confused you!)
Ternary Operator: The one and only! It works on three things.
(condition ? valueIfTrue : valueIfFalse)