Intermediate JS Solutions
Warm Up
On each sticky note at your table, write one thing you’ve already learned about JavaScript. If it helps, you can think about this in two categories: data types and concepts.
Data Types:
- Strings
- Numbers
Concepts:
- Variables (storing values in them, re-assigning the values, if values are numbers they can be incremented)
- Interpolation
- Printing out -
console.logandalert
Explore: Operators
Look at each expression below and the value it evaluates to. Based on that information, try to determine what that operator does.
Scholars may take educated guesses and not be sure at this point - that’s ok! For your reference, the actual answers are listed below. During this time, encourage scholars to find the patterns and see if they can write their own definition of each operator.
!==is called the not equal operator. It checks to see if two values (one immediately before and after) are not equal. it will returntrueorfalse.%is called the modulo operator. It divides the number immediately before it by the number immediately after it, and returns the remainder. This can be very helpful when trying to determine if a number is odd or even!
Try It: Comparison Operators
Declare two variables - firstName and age, and assign them to appropriate values. Now, check for the following things:
var firstName = "Tara";
var age = "189";
Is your name the same as “Karlie”? firstName === "Karlie"
Is your age the same as 15? age === 15
Is your age not the same as 15? age !== 15
Is your age greater than 7? age > 7
Is your age less than or equal to 10? age <= 10
What is the remainder when you age is divided by 2? age % 2
Medium Challenge: 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.
var fakePassword = "h3ll0w0rld!";
fakePassword.length >= 8
// => true
fakePassword = "h3ll0";
fakePassword.length >= 8
// => false
fakePassword = "h3ll0W0rrrld*&";
fakePassword.length >= 8
// => true
Try It: Conditionals
Create a variable named luckyNumber and assign it to a number of your choice.
var luckyNumber = 7;
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.
if (luckyNumber < 50) {
console.log("whoohoo you're a lucky one!");
} else {
console.log("better luck next time");
}
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…”
var luckyNumber = 7;
if (luckyNumber === 13) {
console.log("You got it!");
} else if (luckyNumber > 13) {
console.log("Guess lower...")
} else {
console.log("Guess higher...")
}
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 the number is from the luckyNumber. There should be one output when the number is within 10 of the lucky number, 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!”.
Option 1:
var luckyNumber = 7;
if (luckyNumber === 13) {
console.log("You got it!");
} else if (luckyNumber >= 3 && luckyNumber <= 23) {
console.log(`So close, you are just ${luckyNumber - 13} off.`);
} else {
console.log(`Ouch you are not even close. Off by ${luckyNumber - 13}!`);
}
Considerations for Option 1:
- It’s pretty straightforward in terms of what we have learned so far, except for the
&&- that might require some research! - In it’s current state, a negative number may print out for either of the “wrong guess” outcomes. That’s not ideal.
- It’s really tied to the fact that the “answer” is 13. Therefore, it’s not very dynamic.
Option 2:
var luckyNumber = 7;
var answer = 13;
var difference = Math.abs(luckyNumber - answer);
if (luckyNumber === 13) {
console.log("You got it!");
} else if (difference <= 10) {
console.log(`So close, you are just ${difference} off.`);
} else {
console.log(`Ouch you are not even close. Off by ${difference}!`);
}
Considerations for Option 2:
- This requires the creation of two new variables that the scholar/person completing this weren’t explicitly told about.
Math.abs()finds the absolute value of a number, so handled the issue in our first solution.- By creating the
answeranddifferencevariables, this solution is more dynamic. It would be easier to change (just in one place) if the “correct answer” were to change.
Try It: Conditionals
Create a variable named favoriteFood and assign it to a string of your favorite food.
var favoriteFood = "Qdoba";
- Write an if statement comparing your favorite to ‘Chipotle’, which if evaluated to true, prints out a sentence of your choice
- Write an else if statement comparing your favorite to ‘Starbucks’, 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
var favoriteFood = "Qdoba";
if (favoriteFood == "Chipotle") {
console.log("What.");
} else if (favoriteFood === "Starbucks") {
console.log("Ok, decent.");
} else if (favoriteFood === "McDonalds") {
console.log("You do you.");
} else {
console.log("You didn't choose Chipotle, Starbucks, OR McDonalds.");
}
//=> "You didn't choose Chipotle, Starbucks, OR McDonalds."
var favoriteFood = "Chipotle";
//->"What."
var favoriteFood = "Starbucks";
//-> "Ok, decent."
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.
var stringToCheck = "hello" // 5 characters, odd
if (stringToCheck % 2 === 0) {
console.log("even");
} else {
console.log("odd");
}
//-> "odd"
var stringToCheck = "hi"
//-> "even"
Practice: JS Foundations
Declare a variable called numberOfScholars and assign it to any number. Write a condition that checks the number of scholars. If there are less than 24, output “There is room for more - welcome!”. If there are already 24 or 25 scholars, output “Oh no, we’re going to have to put you on the waiting list.” If there are more than 25 scholars, output “We are so sorry but we are booked. Would you like to sign up for next year?”
var numberOfScholars = 20;
if (numberOfScholars < 24) {
console.log("There is room for more - welcome!");
} else if (numberOfScholars === 24) {
console.log("Oh no, we're going to have to put you on the waiting list.");
} else if (numberOfScholars === 25) {
console.log("Oh no, we're going to have to put you on the waiting list.");
} else {
console.log("We are so sorry but we are booked. Would you like to sign up for next year?");
}
An alternative to having two
else ifstatements that run the same code if to combine them withelse if (numberOfScholars === 24 || numberOfScholars === 25)
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.
var number = 14;
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);
}
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).
var fakePassword = "H3ll0World!";
var splitPassword = fakePassword.split("");
var containsNumber = false;
splitPassword.forEach(function(char) {
if (!isNaN(parseInt(char))) {
containsNumber = true;
}
});
if (fakePassword.length >= 8 && fakePassword.length <= 14) {
if (containsNumber) {
console.log("Good job including a number.")
} else {
console.log("Oops! It looks like you didn't include a number.")
}
console.log("Good job with the number of characters.");
} else {
console.log("Oops! Make sure your password is between 8 and 14 characters long!");
}