1.4 - Conditionals

Review

  • We now have the ability to write code that takes input (prompt), processes it (math), and gives output (console.log)

  • We know the difference between a number and a String

  • We have learned some Math and String functions that can be really helpful

1.4 - Conditionals

How do we make decisions based on information?

Friend: "Want to go to the movies?"

You: "Only if you pay."

What happens if your friend pays? What else could happen?

Consider a program that determines if a number is even or odd.
Ask the user for a number (or get a random one).
What if they enter a word instead?
Let's say it's a number...
How do we decide if it's even?


[ Slides for today's lesson ] [ Scrim for today's lesson ]

Interesting Notes & Resources:

  • There is an operator that determines the remainder of a division statement.

    • % or "Modulo"

    • Examples: 8 % 3 returns 2, or 9 % 5 returns 4, and 16 % 4 returns 0

    • How could that be used to determine if a number is even or odd?

  • The internet is full of tutorials, more tutorials, and examples about the if-else statement since it is one of the very first constructs people learn in programming.

Extras

  • Here's something weird - try ("A" < "a") or ("A" > "a")

  • Because the if-else condition is boolean logic, you can combine multiple conditions with AND and OR

    • AND uses the operator && and OR uses the operator ||

    • Example:

let x = 5, y = 3;

if ((x < 10) && (y > 1)) {

console.log("Hooray!");

} else {

console.log("Boooo");

}

What will the above code output to the console?