Inside an if or else code block, you can write any code you wish - even another if statement. This is useful for more complex logic.
Let's write a small application that calculates a museum ticket price based on a person's age. Under 18 years old, you get 50% discount from the full price. Otherwise you pay full price.
In addition, we also want to just for a valid age first before calculating the price. Here is how it looks like:
const fullPrice = 7;
if (age >= 0 && age < 120) {
let discount;
if (age < 18) {
discount = 50;
}
else {
discount = 0;
}
const ticketPrice = fullPrice * (discount / 100);
console.log('Your ticket price is €' + ticketPrice.toFixed(2));
}
else {
console.log('Invalid age, no ticket for you')
}
The code above has two if statements:
if that checks if the age is between 0 and 120.if inside of the main if that checks for a person’s age.<aside> ❗
Notice that the code inside the main if is indented - it's moved two spaces to the right. This signals to developers that the entire block of code is nested within an existing code block. It makes the logic easier to follow for others.
</aside>
If the age is not valid, the whole discount calculation is skipped and the main else will print out that invalid age message. This is useful for two reasons:
if condition, we are in a safe zone where we can be sure that the age is valid and between 0 and 120. Because the inner condition age < 18 is in the safe zone, we already know that the age is 0 or higher, so there is no need to check it again.in.Let’s write a coin flip game. Here are the rules:
To simulate a coin flip in JavaScript, we will use the handy Math.random() function:
let score = 0;
if (Math.random() > 0.5) {
console.log('Heads');
score++;
if (Math.random() > 0.5) {
console.log('Heads');
score++;
}
else {
console.log('Tails');
}
}
else {
console.log('Tails');
}
console.log('Game over, your score is: ' + score);
<aside> ⌨️
Hands-on: Run the game above a few times to see different results, then change one rule and test the game again.
</aside>
Note:
Math.random() returns a number between 0 and 1. This means we have a 50% chance of getting a value above 0.5 - the same odds as flipping a coin.The HackYourFuture curriculum is licensed under CC BY-NC-SA 4.0 **
