Core JavaScript

2.2 Truthiness, Control Flow, Strings

# If Statements

if statements are a common construct in most programming languages. Simply put, they are a way to let your program make decisions based on yes - no questions.

if (x == 5) {
  //notice the two equal signs?
}
1
2
3

The example above shows a simple if statement. Inside the parentheses is where you put the question you want the program to ask. Everything and anything that you place inside the parentheses will be boiled down to a yes or no answer.

When asking questions in if statements, comparison operators are used between the values being compared. Greater than >, less than <, equal to ==, greater than or equal to >= and less than or equal to <=, are the comparison operators.

Sometimes you just want to know if something exists or has a value equivalent to true. (See Truthiness below). We can just put a single variable inside the parentheses to check this. We can also add an exclamaition mark in front of the variable to check for the opposite.

let x = 5;
if (x) {
  //x is a non-zero number and x is not null or undefined.
  // read this as "if x"
}

if (!x) {
  //x is zero or undefined or null
  //we would read this as "if not x"
}
1
2
3
4
5
6
7
8
9
10

# Else and Else If

When you need to do things based on both the TRUE and FALSE conditions then you can use an if-else statement.

if (x > 5) {
  // the condition was true.
  // run this code
} else {
  // the condition was false
  // run this code
}
1
2
3
4
5
6
7

MDN reference for comparison operators (opens new window)

At other times you might want to do things based upon multiple possible answers. In these cases we use if {} else if {} else statements.

if (x == 3) {
  // if x is equal to 3
} else if (x == 4) {
  //if x is equal to 4
} else if (x < 3) {
  //if x is less than 3
} else {
  //all other possible answers
}
1
2
3
4
5
6
7
8
9

You can add as many else if( ) conditions between the if and the else statements as you want.

# Two vs Three equal signs

The examples up to this point have all been using two equal signs. This means that we are comparing the values of the two operands.

There is another comparison operator, three equal signs. It compares the two operands to see if they are actually the same object, not just the same value.

let x = 7;
if (x == 7) {
  //this will be true
  //the value inside x and the value of the number 7 are equal
}

if (x === 7) {
  //this is also true
  //the number 7 and the value inside the variable x are the exact same thing
}
1
2
3
4
5
6
7
8
9
10

Up to this point we have only been comparing Primitive values. When dealing with primitives, it will make no difference if you use two or three equal signs. Primitives are just values. When we start comparing Objects, that is when this will matter.

# Compound If Statements

There are two logical operators:

&& - AND
|| - OR
1
2

We can use these inside our if statements to run multiple tests conditions.

You can programmatically ask questions like "is your age over 18 AND do you like to drink?".

let beverage = 'Corona';
let age = 19;
if (age > 18 && beverage == 'Corona') {
  console.log('You are over 18 and drink Corona');
} else {
  console.log('You are not over 18 OR your beverage is not Corona');
}
1
2
3
4
5
6
7

The alternative to using the logical operators && or || is to use nested if statements. Here is the alternate version of the above code, using nested if statements.

let beverage = 'Corona';
let age = 19;
if (age > 18) {
  if (beverage == 'Corona') {
    console.log('You are over 18 and drink Corona');
  } else {
    console.log('You are over 18 but do NOT drink Corona');
  }
} else {
  console.log('you are not over 18');
}
1
2
3
4
5
6
7
8
9
10
11

So, depending what you want to do with the result either could be the appropriate choice for your code.

# Truthiness

Javascript uses the concepts of truthy and falsey. A question may not give you an answer which is exactly TRUE or FALSE. So, there are a handful of things that are considered equal to FALSE. Everything else is considered TRUE.

There are six values that are considered to be falsey in JavaScript.

let a = 0; //the number zero
let b = false; //the Boolean false value
let c = ''; //an empty string
let d = null; // a variable that is intentionally set to empty
let e = undefined; // a variable that has been declared but not assigned a value yet
let f = NaN; // Not a Number - the result of Mathematic operations when a non-numeric input was provided

if (a || b || c || d || e || f) {
  //code here will never run because the values are all Falsey
} else {
  //this code will run
}
1
2
3
4
5
6
7
8
9
10
11
12

EVERYTHING else in JavaScript is considered to be truthy. And I mean EVERYTHING.

# Logical Short-Circuiting

Another use for the Logical operators && and || is in an expression called logical short-circuiting.

This can be like a short hand way of writing an if statement that has no else clause and then runs one command if the if statement is true.

//the if statement version
if (num) {
  console.log('num has a non-zero value');
}

//the logical short circuiting version
num && console.log('num has a non-zero value');
1
2
3
4
5
6
7

# Ternary Statements

Ternary statements are used as a short-hand for if else statements. When you have an if clause AND and else clause and there is one command to run for each condition, then you can use a ternary operator.

These are often used to assign one of two possible values to a variable.

The basic syntax requires a ? and a :. The expression to the left of the question mark is the question you are asking. Between the question mark and the colon is the value to use or command to run if the question was truthy. The expression that comes after the colon is the value to use or command to run if the question was falsey.

let name = id == 1234 ? 'Elle' : 'Dakota';
1

You are also allowed to nest one ternary statement inside another, as the expression on either side of the ':'.

The down-side to using Ternary statements is that they can get very hard to read if you start nesting them.

# Switch Case Statements

If you had an if statement that was going to compare a variable to a finite list of possible values then a useful alternative to all those parentheses and curly braces might be a switch case statement.

Let's say that we have a variable called someName which contains a name. If the name is one of six possible values then we want to do something specific, tailored to that name. If it is not one of the six then we have a generic thing to do.

We use the keyword case to provide a comparison value for someName. Whatever commands that come after a matching case value will run until a break command is encountered.

You can have a list of possible matches written as a series of case statements written one after another with no break between them.

switch (someName) {
  case 'Alex':
    //do something specific to Alex
    //maybe two or three things even.
    break;
  case 'Devon':
  case 'Cara':
    //do something specific to Devon or Cara
    break;
  case 'Riley':
  //do something specific to Riley
  //NO break here
  case 'Cole':
  case 'Bree':
    //do something specific to Cole or Bree OR RILEY
    break;
  default:
  //do something generic
  //this is like the else condition
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

# Strings

A String is a primitive value made up of letters, numbers, and punctuation, wrapped in quotation marks.

There are three possible quotation marks that you are allowed to use in JavaScript.

"  double quotes
' single quotes
` backtick
1
2
3

The single and double quotes can be used interchangeably, as long as, both the starting and ending mark around the string value are the same.

let name = 'Steve';
let last = 'Griffith';
1
2

Using the single quotes is considered the current best standard.

The backtick characters were a new addition to core JS as part of the ES6 update in 2015. When you wrap your String in backtick characters it is called a Template String.

What makes them special is that you can embed other variables or expressions inside the String.

let name = 'Steve';
let message = `Hello, ${name}. Welcome to MAD9014`;
1
2

The variable or expression that gets embedded in the String gets wrapped inside ${ }.

# String Methods

As we already mentioned, Strings in JavaScript are a Primitive datatype.

However, JavaScript also has an Object of type String. When you create a variable and assign a string value to that variable, then JS will quietly create one of these String Objects in the background for you.

This allows us to use the length property and all the String methods like trim, indexOf, split, toUpperCase, toLowerCase, padStart and many others.

JavaScript String Methods

# Concatenating Strings

When you need to combine multiple strings or put together strings and variables, there are three ways to do this. With the concatenation operator +, with the String concat() method, or by using Template Strings.

In JavaScript you will often find that the terms function and method are used interchangeably. Here are a series of videos that show examples of the different methods that are available on String Objects.

Here is the full playlist about many of the JavaScript String methods (opens new window)

# What to do this week

TODO Things to do before next week.

  • Read all the content from Modules 2.1, 2.2, and 3.1.
  • Start working on the Hybrid Exercises
Last Updated: 5/31/2023, 8:15:38 PM