Conditions...

Ya know, if... else.

Oh yeah, the ternary operator.

Conditional

I'll start with the "if" statement.

It checks a condition and, if it's true runs a block of code.

function checkYear(){

let question = prompt("What year is it?");

if (question < 2019){

alert("Stuck in time are we?");

} else if (question == 2019) {

alert("Yes!");

} else {

alert("Time traveler!");

}

}

The if statement evaulates the expression in the parentheses and the answer is either a true or false boolean value.

In the above example, the input is saved as question.

That value is then checked against the given conditions.

If any of the conditions evaulates to true, it's code block will execute.

Otherwise, the default... Your last else block will execute.

Again

To run another block of code should our initial if statement check out false. We need an else clause.

function checkYear(){

let

question = prompt("What year is it?");

if

(question < 2019){

alert("Stuck in time are we?");

} else if (question == 2019) {

alert("Yes!");

} else {

alert("Time traveler!");

}

}

JS is going to check to see if the year input is less than 2019. If it is, you get the alert - "Stuck in time are we?"

If you get it right, you get the, "Yes!"

If it's not either of those 2, it can only be higher than 2019. So, you can leave off actual check.

The last else can be thought of as your, do this if all other conditions fail/are false..

Ternary Operator

It looks like this:

let result = condition ? value1 : value2;

So the conditon gets tested, if it's true you get value1 back. Otherwise, you'll get value2.

function whatYear(){

let guess = prompt("What year is it?")

let tellYear = guess == 2019 ? alert("Nice") : alert("Come on!");

}

Prompt - asking what year it is and saving it to the variable guess.

Then we check to see if the guess equals 2019. If it does, we alert, "Nice". If not, "Come on".

Here is that same function rewritten with the if...else.

function rewhatYear(){

let reguess = prompt("What year is it?")

if (reguess == 2019){

alert("Nice");

} else{

alert("Come On!");

}

}

Multiple "?"

We can use multiple ternary operators instead of if...else statements.

function secondTest(){

let young = prompt("Not to be rude, but enter your 'age':");

let greeting = (young < 25) ? alert("Hey youngster."):

(young < 31 ) ? alert("Hey"):

(young < 65 ) ? alert("Almost time to retire"):

(young == 65 ) ? alert("Retire"):

(young > 65 && young < 95) ? alert("Enjoying retirement?"):

(young > 95 && 100 ) ? alert("Whoa!"):

(young >= 100 ) ? alert("Please tell me your secrets"):

alert("I'm on my way to meet you.");

}

Check the condition, if it is true execute the following code.

Otherwise, JS keeps going until it finds a match or hits the default/ast case.