10. JavaScript: Comparisons & Conditionals

10. JavaScript: Comparisons & Conditionals

Welcome to JavaScript: Comparisons & Conditionals!

🎯 Learning Goals

  • Use comparison operators to compare variables, strings, and numbers
  • Write and understand conditional logic

📗 Technical Vocabulary

  • Boolean
  • Condition
  • Conditionals
  • Evaluate
  • Expression
  • Operators
  • Statement
🐚
Here is a sample CodeSandbox for you to fork and use throughout this lesson → Lesson 11: Comparisons & Conditionals Starter
⛅
Warm-up
Did you know that the average human makes more than 35,000 decisions every day? Today we'll learn how computers make decisions using JavaScript conditionals! Write down 3 decisions you've already made today - from the simplest (like what to wear) to more complex ones.

Conditionals

Every programming language has conditionals. If you’ve worked in Python or Java, you’ve probably seen something similar to what we’ll be working on today!
Conditionals let us instruct our program to do something if a specific condition is met. In one web application, there are hundreds if not thousands of conditionals written into the code. Without conditions, web applications would not be able to do much customization for each user.

Comparison Operators

JavaScript gives us a way to compare values. Each expression below will be evaluated to a boolean (pronounced: boo-lee-uhn) true or false.
3 < 5 //=> true 4 >= 9 //=> false 7 === 7 //=> true "karlie" === "karlie" //-> true "karlie" === "Karlie" //-> false
Notice the ===. This checks if two pieces of data are equal to each other. The assignment operator (=), assigns the value of a variable. These two are very different!
🔎
Explore | Operators
Look at each expression below and the value it evaluates to. Based on that information, try to determine what that operator does.
3 !== 4 //=> true 5 !== 5 //=> false 4 !== 9 //=> true 11 % 2 //=> 1 32 % 6 //=> 2 16 % 3 //=> 1 15 % 3 //=> 0
🔎 Answers!
The not equal operator - !== - checks that two values are not equal. It is the opposite of our === operator. Notice how an ! replaces the first =.
The modulo operator - % - finds the remainder of the two numbers. It is a helpful tool to determine if numbers are even or odd. Learn more here!

Comparing Variables

We can use our comparison operators on variables as well! Let’s look at this example:
var language = "JavaScript"; language === "Javascript" //=> false language === "JavaScript" //=> true "javascript" === language //=> false var year = 2024; var nextYear = 2025; year > 2000 //=> true year != 2020 //=> true year < nextYear //=> true
✏
Try-It | Comparison Operators
For this Try It, write all your code in a new CodeSandbox. You will need to use console.log() to check the output of your statements.
Declare two variables - firstName and age, and assign them to appropriate values. Now, check for the following things:
  • Is your name the same as "Karlie"?
  • Is your age the same as 15?
  • Is your age not the same as 15?
  • Is your age greater than 7?
  • Is your age less than or equal to 10?
  • Is your age less than or equal to 10?
  • What is the remainder when you age is divided by 2?
Click here for Medium Practice đŸŒ¶đŸŒ¶
Have you ever tried to create a password, but the application told you you need at least 8 characters? Time to solve a real-world challenge! Declare a new variable called fakePassword and assign it to a string of your choice. Then, check that the value stored in fakePassword is equal to or greater than 8 characters. Change the string that fakePassword is assigned to a couple times to make 100% sure it's working as expected.
Hint 1
To declare a new variable called fakePassword, use the following code:
var fakePassword = "KodeWithKlossy"
KodeWithKlossy can be replaced with any string of your choice.
Hint 2
To create a conditional statement that checks that the value of fakePassword is equal to or greater than 8 characters, use the following code:
var passwordLength = fakePassword.length
console.log(passwordLength >= 8)
 
Together,
var fakePassword = "KodeWithKlossy"; var passwordLength = fakePassword.length console.log(passwordLength >= 8)
 

The Boolean Game!

Looking for a fun way to put your boolean skills to the test?! Look no further than the Boolean Game!
🃏
Game Rules:
  • You are given a boolean expression and 9 boxes (3 colors x 3 numbers).
  • Put an X in the corresponding light green boxes on the right that satisfy the boolean expression.
  • You will receive 1 point for every correct box you click on.
  • The game is over if you select an incorrect box.
  • As you get more points, the boolean expression will get harder.
  • When the status bar says you've solved the level, proceed to the next level by clicking the next tab along the bottom of the screen.
In the example to the right, you would put an X in the corresponding light green boxes that contain a two, no matter the color!
notion image
 
🟰
Basic Boolean Operations Used in the Game:
  • & (conjunction), denoted x & y, satisfies x & y = 1 if x = y = 1 and x & y = 0 otherwise.
  • or (disjunction), denoted x or y, satisfies x or y = 0 if x = y = 0 and x or y = 1 otherwise.
  • not (negation), denoted not x, satisfies not x = 0 if x = 1 and not x = 1 if x = 0.
  • nor (negation of or), denoted not x & not y, satisfies x nor y = 1 if x = y = 0 and x nor y = 0 otherwise.

Logical Operators

Logical operators allow us to do some even more powerful work - they allow us to check multiple statements in one line! The “or” logical operator - || - checks if one or both of the statements are true, and the “and” operator - && - checks if both statements are true. Logical operators allow us to do some even more powerful work:
var language1 = "JavaScript"; var language2 = "Swift"; console.log(language1 === "JavaScript" || language2 === "JavaScript"); // true console.log(language1 === "Swift" || language2 === "Swift"); // true console.log(language1 === "Python" || language2 === "Python"); // false console.log(language1 === "JavaScript" && language2 === "JavaScript"); // false console.log(language1 === "Swift" && language2 === "Swift"); // false
✏
Try-It | Logical Operators
For this Try It, write all your code in the Sandbox from the previous activity. You will need to use console.log() to check the output of your statements.
Use the same two variables as the previous activity - firstName and age, and assign them to appropriate values. Now, check for the following things:
  • Is your age less than 30 and greater than 10?
  • Is your age less than 20 and greater than 10?
  • Is your age exactly 15 or greater than 18?
  • Is your age less than 12 or exactly 14?
  • Is your age greater than 10 but not exactly 16?

Conditionals

Just like in real life, programming is full of decisions. We usually make decisions based on our current state or mood.
A real-life example:
Am I hungry?
Yes ➡ I’ll eat
No ➡ I won’t eat
A programming example:
Do you have an account?
Yes ➡ Please log in
No ➡ Please create an account
JavaScript gives us a way to ask those questions and provide different outcomes based on the answer. They are called conditionals. Here’s an example:
var queen = "Beyoncé"; if (queen === "Beyoncé") { alert("You are correct!") } else { alert("Beyoncé is the only queen.") }
For the example above, an alert will display the text, “You are correct!”. Let’s break this down line-by-line.
var queen = "Beyoncé"; // new variable created if (queen === "Beyoncé") { // program checks for this condition // if it evaluates to true, it will execute this block alert("You are correct!") } else { // if it evaluates to false, it will execute this block alert("Beyoncé is the only queen.") }
We call this entire piece of code an if statement.
Inside the parenthesis after the keyword if, we have to give JavaScript an expression that can evaluate to true or false. That expression is called a condition.
  • If the condition evaluates to true, the code in the block below it will execute or run. It will then ignore the rest of the options.
  • If it evaluates to false, it will check the condition in the next block.
✏
Try-It | Conditionals
For this Try It, write all your code in your Sandbox from earlier. You will need to use console.log() to check the output of your statements.
  • Create a variable named luckyNumber and assign it to a number of your choice.
  • Write an if statement checking if luckyNumber is less than 50, which if evaluated to true, prints out a sentence (you choose!). If it is evaluated to false, it should print out a different sentence.
Click here for a Medium Challenge đŸŒ¶đŸŒ¶
Using your luckyNumber, write a new conditional. If the lucky number equals 13, the output should be "You got it!". If it is too high, the output should be "Guess lower...", and it is too low, the output should be "Guess higher..."
Hint 1
To check if the lucky number equals 13, use the following code:
if (luckyNumber === 13)
 
If the lucky number is less than 13, use the following code:
else if (luckyNumber < 13)
 
If the lucky number is greater than 13, use the following code:
else if (luckyNumber > 13)
 
Hint 2
if (luckyNumber === 13), then the output should be:
alert(“You got it!”)
 
else if (luckyNumber < 13), then the output should be:
alert(“Guess higher
”)
 
else if (luckyNumber > 13), then the output should be:
alert(“Guess lower
”)
 
Together,
var luckyNumber = 10; // Note: Your luckyNumber can be any number! if (luckyNumber === 13) { console.log("You got it!") } else if (luckyNumber < 13) { console.log("Guess higher...") } else if (luckyNumber > 13) { console.log("Guess lower...") }
Click here for a Spicy Challenge đŸŒ¶đŸŒ¶đŸŒ¶
Using your luckyNumber, write a new conditional. If the lucky number equals 13, the output should be "You got it!". If it is not, the output should be customized based on how far luckyNumber is from 13. There should be one output when the number is within 10 of 13, and one when there's a difference of more than 10. For example, if the number is 20, the output might be: "So close, you are just 7 off.". If the number is 100, the output might be "Ouch you are not even close. Off by 87!".
Hint 1
if (luckyNumber === 13), then the output should be:
console.log(”You got it!”)
 
If not, let’s customize the output based on how far luckyNumber is.
 
If the number is within 10 of 13, use the following code:
else if (luckyNumber >= 3 && luckyNumber <= 24)
 
Otherwise, use the following code:
else
 
Hint 2
else if (luckyNumber >= 3 && luckyNumber <= 24), then the output should be:
 
console.log(`So close! You are just ${Math.abs(13 - luckyNumber)} off! `)
 
where ${Math.abs(13 - luckyNumber)} calculates the difference between 13 and luckyNumber
 
else, the output should be:
console.log(`Not even close. Off by ${Math.abs(13 - luckyNumber)} `)
 
Note the use of ` ` when using variable interpolation.`` must be used as any other quotation marks will not work.
Together,
if (luckyNumber === 13) { console.log("You got it!") } else if (luckyNumber >= 3 && luckyNumber <= 24) { console.log(`So close! You are just ${Math.abs(13 - luckyNumber)} off!`) } else { console.log(`Not even close. Off by ${Math.abs(13 - luckyNumber)}`) }
Sometimes we may want to provide more than two options. Look at the use of else if:
var queen = "Beyoncé"; if (queen === "Beyoncé") { console.log("You are correct!") } else if (queen === "Elizabeth II") { console.log("I guess you are technically right...") } else { console.log("Beyoncé is the only queen.") }
đŸ’Œ
Takeaways:
  • We can use any comparison operator in a condition
  • We can use strings or numbers in a condition
  • If a condition evaluates to true, the code below (block) it will run
  • Only one block of code will run for each if statement
✏
Try-It | More Conditionals
For this Try It, write all your code in your Sandbox.
  • Create a variable named favoriteFood and assign it to a string of your favorite food
  • Write an if statement comparing your favorite to 'Smartfood', which if evaluated to true, prints out a sentence of your choice
  • Write an else if statement comparing your favorite to 'Croissant', which if evaluated to true, prints out a sentence of your choice
  • Write another else if - you choose what you compare it to
  • Write an else statement that prints out a sentence of your choice
  • Try changing the value of your favoriteFood variable to "Smartfood", then "Croissant" (if it wasn't already). Do you get what you expected?
Click here for a Medium Challenge đŸŒ¶đŸŒ¶
Write a program that checks a string. It should print to the console "even" if the number of characters in the text is even, and "odd" if the number of characters in the text is odd.
Hint 1
First, create a string. Use the following code:
var uncheckedString = "steminism”
 
To store the number of characters in the string, use the following code:
var countedString = uncheckedString.length
 
If a string has an even number of characters, its number of characters should be divisible by 2. To check if the number of characters is divisible by 2, use the following code:
var checkedString = countedString % 2
 
 
Hint 2
if (checkedString == 0) , then the output should be:
console.log("Your string is even.")
else, then the output should be:
console.log("Your string is odd.")
 
Note the use of % (the modulo operator). The modulo operator stores the remainder when countedString is divided by 2 inside of checkedString.
If checkedString has an even number of characters, it is divisible by 2. If a number is divisible by 2, then its remainder is 0. So, the modulo operator will return 0.
If checkedString has an odd number of characters, it is not divisible by 2. If a number is not divisible by 2, then its remainder is not 0. So, the modulo operator will not return 0.
Together,
var uncheckedString = "steminism" var countedString = uncheckedString.length var checkedString = countedString % 2 if (checkedString == 0) { console.log("Your string is even.") } else { console.log("Your string is odd.") }
 
 

JavaScript: Comparisons & Conditionals

JavaScript is pretty different from HTML and CSS. It feels like a really different way of thinking for some people! If it’s new and a little uncomfortable for you, that’s ok! Keep asking questions and working together.
📝
Practice | JavaScript: Comparisons & Conditionals
For each of these exercises, you should use a console.log() to print your output or feedback.
  • Declare a variable called temperatureInF and assign it any number.
  • Write a conditional statement that outputs a message based on the value of temperatureInF:
    • If the temperature is less than 60, output: "It’s chilly! Don’t forget a jacket."
    • If the temperature is between 60 and 80 (inclusive), output: "Perfect weather for some outdoor coding!"
    • If the temperature is above 80, output: "Maybe try a cold lemonade and indoor coding."
Click here for a Medium Challenge đŸŒ¶đŸŒ¶
Declare a new variable number and assign it to any number. If it is a multiple of 3, print "Fizz". If it is a multiple of 5, print "Buzz". If it is a multiple of both 3 and 5, print "FizzBuzz". If it isn't a multiple of 3 or 5, just print out the number.
Hint 1
To create a new variable number
var number = 10;
 
If number is a multiple of both 3 and 5, then number is divisible by any multiple of 3 and 5 such as 15. Use the following code:
if (number % 15 == 0)
 
Else if number is a multiple of 3, then number is divisible by 3. Use the following code:
else if (number % 3 === 0)
 
Else if number is a multiple of 5, then number is divisible by 5. Use the following code:
else if (number % 5 === 0)
 
If number isn’t a multiple of 3 or 5, then number is not divisible by 3 and 5. However, we have already checked whether number is divisible by 3 and 5 in our previous lines of code. So, use the following code that is simply the else statement:
else
 
Hint 2
if (number % 15 == 0), then the output should be:
console.log(”FizzBuzz”)
 
else if (number % 3 === 0), then the output should be:
console.log(”Fizz”)
 
else if (number % 5 === 0) , then the output should be:
console.log(”Buzz”)
 
else, the output should be:
console.log(number)
 
Together,
var number = 10 // Note: Your number can be any number! if (number % 15 == 0) { console.log("FizzBuzz") } else if (number % 3 == 0) { console.log("Fizz") } else if (number % 5 == 0) { console.log("Buzz") } else { console.log(number) }
 
Click here for a Spicy Challenge đŸŒ¶đŸŒ¶đŸŒ¶
Have you ever tried to create a password, but the application told you that you need at least 1 number and between 8 and 14 characters total? Time to solve another real-world challenge!
  • Declare a new variable called fakePassword and assign it to a string of your choice.
  • Write a conditional that checks the value of fakePassword and gives appropriate feedback on if it is a valid password (contains at least 1 number and between 8 and 14 characters total).
Hint 1
To create a variable called fakePassword, use the following code:
var fakePassword = “securePassword”;
 
To check the if the length of fakePassword is between 8 and 14 characters, use the following code:
if (!(fakePassword.length >= 8 && fakePassword.length <= 14))
 
To check if fakePassword has at least one number, use the following code:
else if (fakePassword.includes('0') || fakePassword.includes('1') || fakePassword.includes('2') || fakePassword.includes('3') || fakePassword.includes('4') || fakePassword.includes('5') || fakePassword.includes('6') || fakePassword.includes('7') || fakePassword.includes('8') || fakePassword.includes('9'))
 
If fakePassword is not valid, use the following code:
else
We can simply use else because we have already checked if fakePassword is valid in the previous code. So, if it reaches this statement, we know that fakePassword is not valid.
Hint 2
if (!(fakePassword.length >= 8 && fakePassword.length <= 14)), then the output should be:
console.log("Enter a password that is between 8 and 14 characters");
 
else if (fakePassword.includes('0') || fakePassword.includes('1') || fakePassword.includes('2') || fakePassword.includes('3') || fakePassword.includes('4') || fakePassword.includes('5') || fakePassword.includes('6') || fakePassword.includes('7') || fakePassword.includes('8') || fakePassword.includes('9')), then the output should be:
console.log("Valid password!");
 
else, the output should be:
console.log("Enter a password that contains at least 1 number.")
 
Note the use of .includes() which returns true if a string includes a specific string.
Together,
var fakePassword = "securePassword" if (!(fakePassword.length >= 8 && fakePassword.length <= 14)) { console.log("Enter a password that is between 8 and 14 characters"); } else if (fakePassword.includes('0') || fakePassword.includes('1') || fakePassword.includes('2') || fakePassword.includes('3') || fakePassword.includes('4') || fakePassword.includes('5') || fakePassword.includes('6') || fakePassword.includes('7') || fakePassword.includes('8') || fakePassword.includes('9')) { console.log("Valid password!"); } else { console.log("Enter a password that contains at least 1 number.") }
page icon
For a summary of this lesson, check out the 11. JavaScript: Comparison & Conditionals One-Pager!
Â