JavaScript Notes 2

BY Guanqiao Huang

Posted by HUANG on December 25, 2018

CONDITIONAL STATEMENTS

If Statement

In programming, we can also perform a task based on a condition using an if statement:

if (true) {
  console.log('This message will print!'); 
}
// Prints: This message will print!

Notice in the example above, we have an if statement. The if statement is composed of:

  • The if keyword followed by a set of parentheses () which is followed by a code block, or block statement, indicated by a set of curly braces {}.
  • Inside the parentheses (), a condition is provided that evaluates to true or false.
  • If the condition evaluates to true, the code inside the curly braces {} runs, or executes.
  • If the condition evaluates to false, the block won’t execute.

If…Else Statements

If we wanted to add some default behavior to the if statement, we can add an else statement to run a block of code when the condition evaluates to false. Take a look at the inclusion of an else statement:

let sale = true;
sale = false;
if(sale) {
  console.log('Time to buy!');
}else{
  console.log( 'Time to wait for a sale.');
}

An else statement must be paired with an if statement, and together they are referred to as an if...else statement.

In the example above, the else statement:

  • Uses the else keyword following the code block of an if statement.
  • Has a code block that is wrapped by a set of curly braces {}.
  • The code inside the else statement code block will execute when the if statement’s condition evaluates to false.
  • if...else statements allow us to automate solutions to yes-or-no questions, also known as binary decisions.

Comparison Operators

When writing conditional statements, sometimes we need to use different types of operators to compare values. These operators are called comparison operators.

Here is a list of some handy comparison operators and their syntax:

  • Less than: <
  • Greater than: >
  • Less than or equal to: <=
  • Greater than or equal to: >=
  • Is equal to: ===
  • Is not equal to: !== Comparison operators compare the value on the left with the value on the right. For instance:

10 < 12 // Evaluates to true

It can be helpful to think of comparison statements as questions. When the answer is “yes”, the statement evaluates to true, and when the answer is “no”, the statement evaluates to false. The code above would be asking: is 10 less than 12? Yes! So 10 < 12 evaluates to true.

We can also use comparison operators on different data types like strings:

'apples' === 'oranges' // false

In the example above, we’re using the identity operator (===) to check if the string ‘apples’ is the same as the string ‘oranges’. Since the two strings are not the same, the comparison statement evaluates to false.

All comparison statements evaluate to either true or false and are made up of:

Two values that will be compared. An operator that separates the values and compares them accordingly (>, <, <=,>=,===,!==).

//Example
let hungerLevel = 7;
if (hungerLevel > 7){
  console.log('Time to eat!');
}
else{
  console.log('We can eat later!');
}

Logical Operators

Working with conditionals means that we will be using booleans, true or false values. In JavaScript, there are operators that work with boolean values known as logical operators. We can use logical operators to add more sophisticated logic to our conditionals. There are three logical operators:

the and operator (&&)
the or operator (||)
the not operator, otherwise known as the bang operator (!)

When we use the && operator, we are checking that two things are true:

if (stopLight === 'green' && pedestrians === 0) {
  console.log('Go!');
} else {
  console.log('Stop');
}

When using the && operator, both conditions must evaluate to true for the entire condition to evaluate to true and execute. Otherwise, if either condition is false, the && condition will evaluate to false and the else block will execute.

If we only care about either condition being true, we can use the   operator:
if (day === 'Saturday' || day === 'Sunday') {
  console.log('Enjoy the weekend!');
} else {
  console.log('Do some work.');
}
When using the   operator, only one of the conditions must evaluate to true for the overall statement to evaluate to true. In the code example above, if either day === ‘Saturday’ or day === ‘Sunday’ evaluates to true the if‘s condition will evaluate to true and its code block will execute. If the first condition in an   statement evaluates to true, the second condition won’t even be checked. Only if day === ‘Saturday’ evaluates to false will day === ‘Sunday’ be evaluated. The code in the else statement above will execute only if both comparisons evaluate to false.

The ! not operator reverses, or negates, the value of a boolean:

let excited = true;
console.log(!excited); // Prints false
 
let sleepy = false;
console.log(!sleepy); // Prints true

Essentially, the ! operator will either take a true value and pass back false, or it will take a false value and pass back true.

Logical operators are often used in conditional statements to add another layer of logic to our code.

let mood = 'sleepy';
let tirednessLevel = 6;

if(mood === 'sleepy' && tirednessLevel > 8){
  console.log('time to sleep');
}
else{
  console.log('not bed time yet');
}

Truthy and Falsy

Truthy and Falsy Let’s consider how non-boolean data types, like strings or numbers, are evaluated when checked inside a condition.

Sometimes, you’ll want to check if a variable exists and you won’t necessarily want it to equal a specific value — you’ll only check to see if the variable has been assigned a value.

Here’s an example:

let myVariable = 'I Exist!';
 
if (myVariable) {
   console.log(myVariable)
} else {
   console.log('The variable does not exist.')
}

The code block in the if statement will run because myVariable has a truthy value; even though the value of myVariable is not explicitly the value true, when used in a boolean or conditional context, it evaluates to true because it has been assigned a non-falsy value.

So which values are falsy— or evaluate to false when checked as a condition? The list of falsy values includes:

  • 0
  • Empty strings like “” or ‘’
  • null which represent when there is no value at all
  • undefined which represent when a declared variable lacks a value
  • NaN, or Not a Number

Here’s an example with numbers:

let numberOfApples = 0;
 
if (numberOfApples){
   console.log('Let us eat apples!');
} else {
   console.log('No apples left!');
}
 
// Prints 'No apples left!'

The condition evaluates to false because the value of the numberOfApples is 0. Since 0 is a falsy value, the code block in the else statement will run.

let tool = '';

// Use short circuit evaluation to assign  writingUtensil variable below:
let writingUtensil = tool || 'pen';

console.log(`The ${writingUtensil} is mightier than the sword.`);

Ternary Operator

In the spirit of using short-hand syntax, we can use a ternary operator to simplify an if…else statement.

The structure of a ternary operator looks like:

condition ? firstExpression : secondExpression

The firstExpression will execute if condition is truthy. If condition is falsy then the secondExpression will execute.

Take a look at the if…else statement example:

let isNightTime = true;
 
if (isNightTime) {
  console.log('Turn on the lights!');
} else {
  console.log('Turn off the lights!');
}

We can use a ternary operator to perform the same functionality:

isNightTime ? console.log('Turn on the lights!') : console.log('Turn off the lights!');

In the example above:

  • The condition, isNightTime, is provided before the ?.
  • Two expressions follow the ? and are separated by a colon :.
  • If the condition evaluates to true, the first expression executes.
  • If the condition evaluates to false, the second expression executes.

Like if…else statements, ternary operators can be used for conditions which evaluate to true or false.

favoritePhrase === 'Love That!' ? console.log('I love that!') :
  console.log("I don't love that!");

Else If Statements

//Example 1
let stopLight = 'yellow';
 
if (stopLight === 'red') {
  console.log('Stop!');
} else if (stopLight === 'yellow') {
  console.log('Slow down.');
} else if (stopLight === 'green') {
  console.log('Go!');
} else {
  console.log('Caution, unknown!');
}
//Example 2
let season = 'summer';

if (season === 'spring') {
  console.log('It\'s spring! The trees are budding!');
}else if(season === 'winter'){
  console.log('It\'s winter! Everything is covered in snow.');
} 
else if(season === 'fall'){
  console.log('It\'s fall! Leaves are falling!');
}
else if(season === 'summer'){
  console.log('It\'s sunny and warm because it\'s summer!');
}
else {
  console.log('Invalid season.');
}

For those who are curious about else if statement in ternary operator

function example(…) {
    return condition1 ? value1
         : condition2 ? value2
         : condition3 ? value3
         : value4;
}

// Equivalent to:

function example(…) {
    if (condition1) { return value1; }
    else if (condition2) { return value2; }
    else if (condition3) { return value3; }
    else { return value4; }
}

The switch keyword

//Example 1
let groceryItem = 'papaya';
 
switch (groceryItem) {
  case 'tomato':
    console.log('Tomatoes are $0.49');
    break;
  case 'lime':
    console.log('Limes are $1.49');
    break;
  case 'papaya':
    console.log('Papayas are $1.29');
    break;
  default:
    console.log('Invalid item');
    break;
}
 
// Prints 'Papayas are $1.29'
//Example 2
let athleteFinalPosition = 'first place';
switch(athleteFinalPosition){
  case 'first place':
  console.log('You get the gold medal!');
  break;
  case 'second place':
  console.log('You get the silver medal!');
  break;
  case 'third place':
  console.log('You get the bronze medal!');
  break;
  default:
  console.log('No medal awarded.');
  break;
}
//Magic Eight Ball
let userName = 'Daniel';
userName?console.log(`Hello,${userName}!`):console.log('Hello!');
let userQuestion = 'What is Salesforce?';
console.log(`Hi ${userName},${userQuestion}`);
let randomNumber = Math.floor(Math.random()*8);
let eightBall = '';
switch (randomNumber){
  case 0:
  eightBall = 'It is certain';
  break;
  case 1:
   eightBall = 'It is decidedly so';
  break;
  case 2:
   eightBall = 'Reply hazy try again';
  break;
  case 3:
  eightBall = 'Cannot predict now';
  break;
  case 4:
  eightBall = 'Do not count on it';
  break;
  case 5:
  eightBall = 'My sources say no';
  break;
  case 6:
  eightBall = 'Outlook not so good';
  break;
  case 7:
  eightBall = 'Signs point to yes';
  break;
}
console.log(eightBall);

Math.random() returns a value between 0 (inclusive) and 1 (exclusive).

In order to make this set of numbers range from 0 (inclusive) to 1000 (exclusive) we can multiply the returned value by 1000.

Finally, to ensure we only have whole numbers from 0 to 999 we can round down using Math.floor().

//Race Day
let raceNumber = Math.floor(Math.random() * 1000);
let registeredEarly = false;
let runnerAge = 20;
runnerAge >= 18 && registeredEarly === true ?raceNumber += 1000:raceNumber += 0;
if(runnerAge >= 18 && registeredEarly){
 // raceNumber += 1000;
  console.log(`RaceNumber: ${raceNumber} - 9:30am`);
}
else if(runnerAge >= 18 && !registeredEarly){
  console.log(`RaceNumber: ${raceNumber} - 11:00am`);
}
else if(runnerAge < 18){
  console.log(`RaceNumber: ${raceNumber} - 12:30pm`)
}

Review

Way to go! Here are some of the major concepts for conditionals:

  • An if statement checks a condition and will execute a task if that condition evaluates to true.
  • if…else statements make binary decisions and execute different code blocks based on a provided condition.
  • We can add more conditions using else if statements.
  • Comparison operators, including <, >, <=, >=, ===, and !== can compare two values.
  • The logical and operator, &&, or “and”, checks if both provided expressions are truthy.
  • The logical operator   , or “or”, checks if either provided expression is truthy.
  • The bang operator, !, switches the truthiness and falsiness of a value.
  • The ternary operator is shorthand to simplify concise if…else statements.
  • A switch statement can be used to simplify the process of writing multiple else if statements. The break keyword stops the remaining cases from being checked and executed in a switch statement.