Scripts often need to behave differently depending upon how the user interacts with the web page and/or the browser window itself.
Comparison and logic operators will come in handy
> greater than
< less than
>= greater than or equal to
<= less than or equal to
=== strict equality
!== strict ineqality
&& logical AND
|| logical OR
Decision making based on conditions
Conditional statements gives us the ability to check conditions and change the behavior of the program accordingly.
Checks for only one condition
Checks Condition
True/False
Executes Statement
False
True
if (money >= 500) {
return "I'm buying some Yeezys!";
}
Checks for two conditions
Checks Condition
True/False
Statement 1
False
True
Statement 2
if (money >= 500) {
return "I'm buying some Yeezys!";
}else{
return "No fresh kicks for me.";
}
Checks for more than two conditions
Checks Condition
True/False
Statement 2
False
True
Statement 1
Next Condition
True/False
True
Statement 3
False
if (money < 10) {
return "Love dem Old Navy clearance!";
} else if (money < 20){
return "Stepping up to da GAP!";
}else{
return "I fancy with Banana Republic."
}
Sometimes you'll need to evaluate many different conditions.
Best practice is to use switch statements if you are evaluating 3 or more conditions.
var day = 'Friday';
var menu = null;
switch (day) {
case 'Monday':
menu = 'burgers';
break;
case 'Tuesday':
menu = 'tacos';
break;
case 'Wednesday' :
menu = 'chicken katsu curry';
break;
case 'Thursday' :
menu = 'pizza';
break;
case 'Friday' :
menu = 'poke bowl';
break;
default:
menu = 'spam musubi';
}
console.log(menu);
Automates repetitive tasks
Thee types of loops:
Iterates/traverses over a sequence
each item in sequence
Last item reached?
Y/N
Back to sequence
Yes
No
Exit Loop
for (var i = 0; i<10; i ++){
//your code
}
var shoppingList = ['carrot cake', 'Doritos', 'peanut butter', 'poke'];
for(var i = 0; i<shoppingList.length; i++){
console.log(shoppingList[i]);
};
Keeps running as long as the condition is true.
Enter While Loop
Condition
T/F
Back to Condition
False
True
Exit Loop
while (i < 20){
//condition
}
var damage = 3;
while(damage < 10){
console.log('You still kicking!');
damage++;
}
do{
//condition
}while (i < 1){
//condition
}
var i = 11;
do{
console.log('print this at least once');
i++;
}while(i<10);
Looping through an Object
for in loop:
var plateLunch = {
menu: ['Chicken Katsu', 'Loco Moco', 'Crab ragoon'],
restaurant: 'Mililani Restaurant',
price: 11,
kanakAttack: true
}
for(key in plateLunch){
console.log(plateLunch[key])
}