Code highlights logo

Learn

Conditional Statements

Truthy and Falsy Assignment

To assign a default value to a variable if it is not defined or evaluates to a falsy value, we can use the concept of truthy and falsy assignment. This allows us to provide a fallback value when the original value is falsy.

1let myVariable = falsyValue || fallbackValue;

In the above code, if falsyValue is falsy, the assignment will evaluate to fallbackValue. Otherwise, if falsyValue is truthy, the assignment will evaluate to falsyValue. This is because the logical OR (||) operator returns the first truthy value it encounters or the last value if all operands evaluate to falsy.

Let's see some examples to better understand truthy and falsy assignment:

1let username = '';
2let displayName = username || 'Guest';
3console.log(displayName); // Output: Guest
4
5let age = 0;
6let userAge = age || 25;
7console.log(userAge); // Output: 25
8
9let message;
10let defaultMessage = message || 'No message found';
11console.log(defaultMessage); // Output: No message found

In the above examples, if the value of the variable on the left side of the || operator is falsy, the fallback value on the right side of the operator is assigned to the variable.

Benefits of Truthy and Falsy Assignment

Using truthy and falsy assignment can be beneficial in various scenarios, including:

  • Assigning default values to variables if they are not defined or evaluate to falsy values.
  • Providing fallback values for optional function arguments.
  • Handling user inputs or form submissions where empty or falsy values need to be handled appropriately.

Instructions

1.

Change the initial value for the variable score to 85.

2.

Modify the If score is truthy message variable to be:

1Congratulations, you passed the test!

Sign up to start coding

Already have an account?

Sign In

Course content