Conditionals
If Statements
let isOne = true;
if(isOn == true){
console.log("The light is on!");
};
An "if statement" is used to run a block of code based on whether a condition is true or not. notice, that 'if' is lowercase. This is usually used if you need your program to make a decision.
Else Statements
let weather = 75;
if(weather < 70){
console.log("Wear a jacket");
} else {
console.log("No jacket necessary!");
};
Similar to the "if statment", this type of code is used whether a condition is true or not, however, this code has an alternative set of instructions, based on whether another factor in your code is true or false.
Else If Statements
let fb = 100;
if(fb % 3 == 0 && fb % 5 == 0){
console.log(FizzBuzz");
} else if(fb % 3 == 0){
console.log("Fizz");
} else if(fb % 5 == 0){
console.log("Buzz");
} else{
console.log(fb);
};
This is an extension of the "else statement". This type of code has many branches of statements available to run, based on what factors may be true in the code.
Switches
var friend = "Brandon"
switch(friendTwo) {
case "Brandon":
console.log("That is my name!");
break;
case "Justis":
console.log("You are my desk neighbor");
break;
case "Kito":
console.log("You play Warhammer 40k");
break;
case "Sean":
console.log("You're bald!");
break;
default:
console.log("Its nice to meet you!");
};
This is alternative form of conditionals. Great for use on items that have many conditions. The default line at the end is a catchall: whatever doesn't work for the rest of the conditional, gets executed here.
Ternary
let x = 14;
(x >= 10) ? console.log(true) : console.log(false);
Ternary is a great way to write an if statement in a single line. Ususally used when only a few outcomes are required, but can be used for any amount.