JS CONDITIONAL STATEMENTS Flashcards
Conditional Statements are used complete a certain action (Or line(s) of code) based on a condition(s)
IF
if (condition) {
CODE TO BE RUN GOES HERE;
}
// Code inside brackets will run if the condition/value is true (NOTE: Remember to use parentheses () around the condition/value)
IF and ELSE
if (condition) { CODE TO BE RUN GOES HERE; } else { CODE TO BE RUN GOES HERE; }
// Code in ELSE brackets runs when the IF condition/value is NOT True. Also, when the IF condition/value is True the code in the IF brackets will run but the code in the ELSE brackets will NOT run.
IF and ELSE IF
if (condition) {
CODE TO BE RUN GOES HERE;
}else if (condition){
CODE TO BE RUN GOES HERE;
}
Code in ELSE IF brackets runs if previous condition(s) are NOT true and the condition for that ELSE IF is True.
// NOTE: While there can only be a single IF and a single ELSE in a conditional statement, there is no limit to the amount of ELSE IFs that can be used in a conditional statement.
IF, ELSE IF, and ELSE
if (condition) { CODE TO BE RUN GOES HERE; } else if (condition) { CODE TO BE RUN GOES HERE; } else { CODE TO BE RUN GOES HERE; }
// Code in ELSE brackets will always run as long as previous conditions are False (NOTE: ELSE does have a condition that needs to be met for it to run)
Nested Conditional Statements
if (true) { console.log("Hello"); if (false) { console.log("Hi"); } } else { console.log("Goodbye"); }
// A conditional statement can be nested inside another conditional statement // In this example the console.log("Hi") will only run when both the very first IF condition is True and the nested IF condition is True