In this lesson, we learn about a shorthand way to check if a value is defined or not. The concept of truthy and falsy values comes into play here. Truthy values are values that are considered “true” when evaluated in a boolean context, while falsy values are values that are considered “false” when evaluated in a boolean context. Examples of truthy values include non-empty strings, non-zero numbers, and objects, while examples of falsy values include empty strings, zero, null, and undefined.
We are given two examples to illustrate this concept. In the first example, we check if a value is defined using an if-else statement. If the value is defined, we assign that value to a variable; otherwise, we assign a default value to that variable. This method works fine, but it takes many lines of code to accomplish a simple task.
In the second example, we learn about short-circuit evaluation, which allows us to write a more concise and readable code. We use the logical OR operator to check if a value is defined or not. If the value is truthy, we assign it to a variable. If it is falsy, we assign a default value to the variable. The logical OR operator works because it returns the first truthy value it encounters or the last value if no truthy value is found.