Open CheatSheet Back To List Next Tutorial

If Statements and Booleans

Intro

  • This tutorial covers Booleans and Conditional statements.
  • Conditional statements execute only if a specified condition is true. The most commonly used conditional is an if statement. 

  • It is recommended that you follow along with each section below. Paste or type the code into your own JavaScript file and view the variable or expression values either with console.logs or using the VS Code Debug sidebar. 

  • The example code for the entire tutorial series is at github.com/LearnByCheating/javascript-tutorial. There is a separate file or folder for each tutorial, including the To-Do List example project. The Readme file has instructions on how to run the code.


Booleans

1. Boolean: data type and global object


  • Conditional statements use Boolean values to determine whether to execute a block of code, so we will cover Booleans first.
  • Boolean is a primitive data type.
  • It has only two possible literal values: true or false.
  • True and false are JavaScript keywords, so they are not in quotes. 

  • The typeof operator returns the data type of a value. 
  • let val = typeof true; // returns 'boolean'
  • val = typeof false; // returns 'boolean'
  • val = typeof 'true'; // returns 'string'

  • The most commonly used primitive data types include strings, numbers, and booleans.
  • Primitive values are generally represented directly at the lowest level of the language implementation. So they are fast and efficient.

  • Like Strings and Numbers, Booleans have a prototype object. You can see it in your code by calling Object.getPrototypeOf passing in true or false.
val = Object.getPrototypeOf(true); // returns Boolean

Boolean prototype properties/methods:
  • The Boolean prototype is a built-in global object that contains properties and methods you can apply to boolean values. 
  • Running the below method will return all the property names.
val = Object.getOwnPropertyNames(Boolean.prototype);

  • This shows there are three properties in the Boolean prototype: constructor, toString, and valueOf. Let's go through each. 

Constructor function: The presence of a constructor function means that new objects can be generated by calling the constructor with the new operator. 
  • That means there are two ways a Boolean value can be represented. As a primitive true or false value, or as an object that holds true or false values. Below is a boolean primitive.

let bool = 1 < 2; 
bool; // returns true
let boolType = typeof bool; // 'boolean'

  • Now we'll create a Boolean object by calling the Boolean constructor function passing in an expression that resolves to a boolean. The expression 1 is less than 2  resolves to true.
bool = new Boolean(1 < 2); // returns a Boolean object
booltype = typeof bool; // returns 'object'

  • Bool now contains a Boolean object with value true. 
  • Unless you have some specific reason to create a Boolean as an object, style guides recommend using Boolean primitive values true and false, not Boolean objects.

Boolean Instance Methods:
  • Methods attached to the prototype are called instance methods because they can be applied to a specific boolean value. To call them you chain them to the Boolean value.

Boolean.prototype.valueOf method:
  • The valueOf instance method converts Boolean objects to Boolean primitive values. 
let boolObj = new Boolean(1 < 2); // creates a boolean object
boolType = typeof boolObj; // returns 'object'
let boolPrim = boolObj.valueOf(); // returns true
boolType = typeof boolPrim; // returns 'boolean'
  • The above code creates a Boolean object called boolObj that contains the value true.
  • Then converts it to a boolean primitive value true with boolObj.valueOf()

Boolean.prototype.toString method:
  • The toString instance method will convert a boolean value to a string. 
val = true.toString(); // returns the string 'true'
val = false.toString(); // returns the string 'false'


2. Boolean: truthy/falsy

  • You can convert any value to true or false using the Boolean function in a non-constructor context, meaning without the keyword new.
  • Pass in a value as the argument and the Boolean function will determine if it is truthy or falsy. 
  • Truthy values resolve to true. Falsy values resolve to false. 

  • Falsy: Falsy values include just these 6 values: false, an empty string "", the number 0, the number value NaN, null, and undefined.
  • Truthy: Everything else is truthy. That includes true, all non-empty strings, all numbers except 0 and NaN, all objects, all arrays.

You can test these in your code. The below resolve to false:
let bool = Boolean(false);
bool = Boolean(""); 
bool = Boolean(0);
bool = Boolean(NaN);
bool = Boolean(null);
bool = Boolean(undefined);

The below resolve to true:
bool = Boolean(true);
bool = Boolean("some text"); // any non-empty string bool = Boolean(" "); // a string with just a single space resolves to true bool = Boolean("false"); // even the string 'false' resolves to true
bool = Boolean(1); // any number but 0
bool = Boolean({}); // any object, even an empty one
bool = Boolean([]); // any array, even an empty one

You can apply the Boolean function to an expression and it will resolve the expression to a value, then convert the value to a Boolean.
let bool = Boolean(1 + 2); // the expression resolves to 3 which the Boolean function converts to true
let x;
bool = Boolean(x); // x is undefined which Boolean() converts to false;

!! converts a value to a Boolean
The ! NOT operator will convert the value to a Boolean, then returns the opposite.
Two !! NOT operators will essentially do the same as applying the Boolean function.
let bool = Boolean('Some string'); // returns true.
bool = !"Some string"; // returns false
bool = !!"Some string"; // returns false
Prefer applying the Boolean function over using !! since it is more explicit.


3. Boolean Expressions: comparison and logical operators

  • A Boolean literal value is true or false. 
  • A Boolean expression is any code the resolves to true or false. 

Comparison operators
Comparison operators that check equality or greater than and less than form expressions that resolve to Boolean values.

Examples:
  • let bool = (1 < 2); resolves to true
  • bool = (typeof true === 'boolean'); typeof true resolves to 'boolean', so this comparison is true. 
  • bool = (typeof 'true' !== 'boolean');
    • The comparison operator is checks if the expressions are NOT equal. 
    • typeof 'true' resolves to 'string' since true is in quotes, so these are not equal.
    • Since we are testing inequality, the overall result is true. 'String' is not equal to 'boolean'.

Logical operators
Logical operators let you evaluate two or more expressions together.

Logical AND:
  • The AND operator, which is two && characters, resolves to true if both expressions are truthy.
bool = (0 < 1) && (a < b); // returns true
  • In the above example, both expressions are true. Since both expressions are true the logical AND expression resolves to true. 

bool = (0 < 1) && (b < a); // returns false
  • In the above example, the first expression is true but the second is false. Since one of the expressions is false the whole logical AND expression resolves to false.

Logical OR:
  • The OR operator, which is two vertical bars ||, resolves to true if one or both of the expressions is true.
bool = (0 < 1) || (a < b); // resolves to true true, and returns true.
bool = (1 < 0) || (a < b); // resolves to false true and returns true.
bool = (0 < 1) || (b < a); // resolves to true false and returns true.
bool = (1 < 0) || (b < a); // resolves to false false and returns false.

  • In the above example the first three expressions resolve to true because one or both of the expressions is true.
  • The last expression is false since both expressions are false.

NOT operator:
  • The not operator is an exclamation mark ! placed in front of the expression. It returns the opposite boolean value as the expression.
bool = !true; // returns false
bool = !(2 < 1); // returns true bool = !"Some string" // returns false
  • In the first example above, the not operator in front of true so the result is false.
  • On the next line we apply the not operator in front of the expression 2 < 1, which resolves to false. But placing the not operator in front of it changes it to true. 
  • On the last line ! does type conversion, converting the string "Some string" to the boolean true, then returns the opposite value false.


Conditional Statements

4. If...Else Statements

  • An if statement is a block of code that executes if its condition resolves to true. If the condition resolves to false it is skipped.
  • When evaluating the condition, the same rules are used as when calling the Boolean function.
    • Comparison operators like equal to, not equal to, greater than, less than, etc. resolve to true or false. if (1 < 2) { statements; }
    • If there are multiple expressions in the condition: 
      • logical AND resolves to true if both expressions are true. 
        • if (expr2 && expr2) { statements; } 
      • Logical OR resolves to true if at least one expression is true.
        • if (expr2 || expr2) { statements; } 
    • Placing the NOT operator in front of an expression returns the opposite Boolean value as the expression.
      • if (!expr) { statements; } 
    • Non-boolean expressions are converted to Booleans. Truthy expressions resolve to true. Falsy expressions resolve to false.

const name = 'Joey';
if (name) {
  console.log('The user's name is ' + name);
}

      • In the above example, the variable name has a string value which converts to true, making the condition true.

If Statement Syntax:
  • The syntax is the keyword if, followed by the condition in parentheses, then the block.
  • Put semicolons after each statement but not after the block.

Format:
if (condition) { 
statements;
}

Example:
const score = 77;
let pass = false;
if (score >= 60) {
  pass = true;
}
pass; // returns true

If... else:
It can have an else clause that executes if the condition is false.

Format:
if (condition) { 
statements;
} else {
statements;
}

Example:
const score = 77;
let pass;
if (score >= 60) {
  pass = true;
} else { pass = false; }
pass; // returns true

If... else if... else:
You can have multiple if clauses by including else if clauses.
Format:
if (condition1) { 
statements;
} else if (condition2) {
statements;
} else {
statements;
}

Example:
let grade;
const score = 77;
if (score >= 90) {
  grade = 'A';
} else if (score >= 80) {
  grade = 'B';
} else if (score >= 70) {
  grade = 'C';
} else if (score >= 60) {
  grade = 'D';
} else {
  grade = 'F';
} grade; // returns 'C'

Block Scoped

  • If statement clauses are code blocks enclosed in curly braces.
  • Variables declared with const or let are block scoped, so variables declared inside an if statement block cannot be accessed outside the block. 

Example:
const score = 77;
if (score > 60) {
  let pass = true;
}
pass; // throws ReferenceError: pass is not defined

To resolve this, declare the variable outside the block:
const score = 77;
let pass = false;
if (score > 60) {
  pass = true;
}
pass; // returns true

Short syntax:
  • There is an optional short syntax for single statement if statements.
  • You can leave off the curly braces and put the statement to execute after the condition. That way you have the whole thing on one line. 


Format:
if (condition) statement;

Example:
const score = 77;
let pass = false;
if (score >= 60) pass = true;


Ternary Statement
  • The Conditional Ternary Statement is a very handy short syntax that includes both an if true clause and an else clause. They are useful for else/if statements that are short enough to put on one line. 

Format:
  • Put the condition first followed by a question mark. 
  • Then the statement to execute or value to return if the condition is true, followed by a colon.
  • Then the statement to execute or value to return if the condition is false.
condition ? resultIfTrue : resultIfFalse;

Example:
const score = 77;
const pass = (score >= 60) ? true : false; pass; // returns true

  • The above example checks if the score is 60 or more. If so then the statement resolves to true. If not it resolves to false. We assign the result to the pass variable.


5. Switch Statement

  • Switch statements are an alternative to if statements if you have multiple else if clauses. They aren't used frequently but they are an option.

Format:
switch (expression) { 
case value1: { statements;
break; }
case value2: { statements;
break; }
default: { statements; }
}

  • Switch: Start with the switch keyword and an expression. 
  • Case: For each alternative use the case keyword followed by the value to compare to the switch expression. Switch statements can only test for strict equality. If they are equal, then the case is true and the block gets executed. 
  • Break: To exit the switch statement when the case is true, use the break statement. Otherwise the other statements below will continue to be tested. 
  • Default: At the bottom you can add an optional default value.

Example:
let grade;
const score = 77;
switch (true) {
  case (score >= 90): {
    grade = 'A';
    break;
  }
  case (score >= 80): {
    grade = 'B';
    break;
  }
  case (score >= 70): {
    grade = 'C';
    break;
  }
  case (score >= 60): {
    grade = 'D';
    break;
  }
  default: {
    grade = 'F';
  }
} grade; // returns 'C'
  • The above switch statement determines the grade based on the score.
  • The switch expression is the value true.
  • Each case uses a comparison operator to check if the score is greater than or equal to the minimum score for that grade. The first case to return true sets the grade value and breaks out of the switch statement.
  • The score of 77 matches the case third case (score >= 70), sets grade to 'C', and breaks out of the switch statement.


Conclusion

The topics in this tutorial correspond with the JavaScript CheatSheet Conditionals/if statements category. Make sure you understand each topic so you can refer back to the CheatSheet when working on your own projects.

If you have the CheatSheet desktop app and downloaded the JavaScript CheatSheet, then go through the flashcards for this category to the point where you can answer them all in order and shuffled.
Open CheatSheet Back To List Next Tutorial