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

If-else statements

Conditions allow a program to make decisions. They let your code choose different paths based on whether something is true or false. Instead of running every line the same way each time, conditions introduce logic: “If this happens, do that - otherwise, do something else.” They are the foundation for all meaningful programs, from validating user input to controlling game mechanics.

You can look at conditions as different paths you can take in the park. You can read the sign to understand what path you need to take and choose one over the other.

image.png

Cute introduction video

Watch the following video to understand if statements.

<aside> 💭

This video is written for Java, C, and C++, but the concepts apply to JavaScript as well.

</aside>

https://www.youtube.com/watch?v=HQ3dCWjfRZ4

A basic example

In JavaScript, we use the special if and else keywords to use conditions.

Here is a basic example

const grade = 78;
if (grade > 60) {
  console.log('You passed');
}
else {
	console.log('You failed');
}

Let's break down what's happening in this code:

In this example, since 78 is greater than 60, the condition is true, so the programme will output 'You passed'. The else block is completely skipped.

<aside> 💭

A code inside a curly braces { } is often called a code block

</aside>

<aside> 💭

At any time, only one path will be chosen. Both paths will never run at the same time.

</aside>

<aside> 💡

The else part is always optional.

</aside>

Another video

Watch the video to if and else in JavaScript

https://www.youtube.com/watch?v=IsG4Xd6LlsM

Another example

// Setup prompt-sync to get user input from the console
import promptSync from "prompt-sync";
const prompt = promptSync();

// Ask user for input
let score = prompt('Enter your test score: ');

// Convert input to a number so we can use mathematical comparisons
score = Number(userInput);

// 60 - 100 -> pass
// 0 - 59   -> fail
if (score >= 60 && score <= 100) {
  console.log('You passed!');
} 
else if (score < 60 && score >= 0) {
  console.log('You failed. Please try again.');
} 
else {
  console.log('Invalid score. Please enter a number between 0 and 100.');
}

<aside> ⌨️

Hands on

  1. Copy the code above into a new file
  2. Run the code (remember to install prompt-sync) and test it with different inputs
  3. Change the code so the passing score is 80 instead of 60 </aside>

Compound if statements

You surely have noticed that some if statements can have multiple conditions combined with AND (&&) and OR (||) operators. Those can be useful to combine to make more complex logic. Those can be also combined with the NOT (!) operator.

Study the following tables below to understand how the logic works between the different operators

AND &&

Both conditions must be true

X Y X && Y
False False False
True False False
False True False
True True True

OR ||

One of the conditions must be true

| X | Y | X || Y | | --- | --- | --- | | False | False | False | | True | False | True | | False | True | True | | True | True | True |

<aside> 💭

Unlike natural language, "OR" in programming is also true when both conditions are true.

</aside>

!X

Reverse the statement’s condition

X !X
False True
True False

Compound if example

Study the example above. It has a useful idea of saving the boolean result in a constant. This can be useful to make your code more readable:

import promptSync from "prompt-sync";
const prompt = promptSync();

let score = prompt('Enter your test score: ');
score = Number(score);

const passed = score >= 60 && score <= 100;

if (!passed) {
  console.log('Unfortunately, you did not pass. Better luck next time!');
} else {
  console.log('Congratulations! You passed the test.');
}

<aside> ⌨️

Hands on: Change the code above to use the OR (||) operator instead of && while keeping the same logic of checking the score.

</aside>

Using parenthesis

Just like in mathematics, using parentheses to group and prioritise complex conditions is important:

if ((day === 'Sunday' || day === 'Monday') && month !== 'December') {
   // Day is 'Sunday' or 'Monday but not in December.
}

Take a few minutes to understand the example above.

<aside> ⌨️

</aside>

Summary of the common operators

Here are the most common operators you should know so far

| --- | --- | --- |

<aside> ❗

</aside>

The ternary operator

When a condition is simple, a full if / else structure can make the code long. In these cases, you can use the ternary operator instead. Here's an example:

const status = age >= 18 ? 'adult' : 'minor';

“status” will be “Adult” or “minor” according to the age >= 18 condition.

Here is the regular if version of the code:

const status;
if (age >= 18) {
  status = 'adult';
} else {
  status = 'minor';
}

When deciding which approach to use, focus on code readability. To the computer, both methods are identical.

Switch

A switch statement is an alternative to using multiple if-else statements. You easily define multiple cases:

import promptSync from "prompt-sync";
const prompt = promptSync();

let month = prompt('Enter a month (1-12): ');
month = Number(month);

switch (month) {
  case 1:
    console.log('January has 31 days');
    break;
  case 2:
    console.log('February has 28 days');
    break;
  case 3:
    console.log('March has 31 days');
    break;
  case 4:
    console.log('April has 30 days');
    break;
  case 5:
    console.log('May has 31 days');
    break;
  case 6:
    console.log('June has 30 days');
    break;
  case 7:
    console.log('July has 31 days');
    break;
  case 8:
    console.log('August has 31 days');
    break;
  case 9:
    console.log('September has 30 days');
    break;
  case 10:
    console.log('October has 31 days');
    break;
  case 11:
    console.log('November has 30 days');
    break;
  case 12:
    console.log('December has 31 days');
    break;
  default:
    console.log('Not a real month');
}

A case runs if the value in the switch parentheses matches the case value. The break statement terminates execution, preventing the code from continuing to the next case once a condition is met. The default block runs if none of the cases match the condition.

<aside> 💡

</aside>