Booleans

  • If you want to assign a boolean to a variable, just use the literals true and false.

    Set the values below as appropriate using the assignment syntax we just learned about.

    Show hint

    To set trueVal to true, you'd just type:

    trueVal = true;

  • In JavaScript, there are 6 "falsy" values (values that evaluate to false):

    false, null, undefined, 0, "" (the empty string), and NaN

    Anything else evaluates to true.

    Hit enter to continue.

  • The bang operator (!) is used to change a truthy value to a falsy value or vice versa.

    For instance, !true is false. Similarly, !null is true because null is falsy.

    We can use this to check if something is not true.

    Work through the example and then hit enter to continue.

    Show hint

    If we have a variable value, we can use if(!value) to check if the value is falsy.

  • You might've been wondering why we've been using === instead of == to check for equality and !== instead of != to check for inequality.

    In JavaScript, == coerces values, which can lead to very unexpected results. If you're not familiar with type coercion, don't worry about the details; just remember to use === and !==.

    Take a look at the sample code to see how == can be confusing.

  • Now, let's try writing a function that checks if a variable is "unset". We consider a variable unset if it is undefined or null.

  • We can actually write these functions more concisely. For instance, isUndefined can be written in one line. Since value === undefined evaluates to a boolean, we can return this directly.

    Take a look at the example and think this through. Then, try to implement isUnset. Make sure you use the more concise syntax for this example. You should not need to use an if statement.

    Show hint

    If you're not familiar with the || operator, you can think of it as 'OR.' If the statement on the left or right is true, it will be true.

Keyboard shortcuts: Run CTRL + Enter Reset CTRL + S