Week 2 - Programming basics

JavaScript

Basic Syntax

Variables

Data types

Numbers

Basic IO

Conditionals

Nested conditions

Git branches

GUI Tools for Git

Code style: Basics

Introduction to AI

Practice

Assignment

Back to core program

Nested conditions

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.

Example

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:

  1. A main if that checks if the age is between 0 and 120.
  2. A second 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:

  1. It is more efficient - we don’t want to run unnecessary code. It is wasteful to calculate a discount for invalid age input.
  2. It is more safe - Inside the main 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.

A small game

Let’s write a coin flip game. Here are the rules:

  1. Flip a coin for the first time.
  2. If it's tails, you lose and the game is over.
  3. If it's heads, you earn one point and flip the coin again.
  4. If the second flip is heads, you earn another point.
  5. The game ends after two flips or when you get tails.

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:


The HackYourFuture curriculum is licensed under CC BY-NC-SA 4.0 **

CC BY-NC-SA 4.0 Icons

*https://hackyourfuture.net/*