If statements are pretty self explanatory. The statement tests “if” a condition within the parentheses is true. If the condition is true, the code is executed. Like so:
if (5 < 6) {
document.write("Our first if statement!");
}
All of the conventions for using conditional and logical operators remain true when we use them in if statements.
Examples:
let name = "Bob";
if (name === "Bob") {
console.log("Hi Bob!");
}
x = 20;
y = 30;
if (x > 10 && y < 50) {
console.log("True!");
}
let secondName = "Todd";
if (secondName === "John") {
console.log("Hello, John!");
} else {
console.log("Hi, " + secondName);
}
See the Pen 3.1 Examples by LSU DDEM (@lsuddem) on CodePen.
—
let name1 = "Todd";
let name2 = "Katy";
let name3 = "Max";
if (name1 == "Katy") {
console.log("Hi, Katy!");
} else if (name1 == "Max") {
console.log("Hi, Max!");
} else {
console.log("Hi, " + name1);
}
See the Pen 3.1 Examples_1 by LSU DDEM (@lsuddem) on CodePen.
let color = "purple";
if (color == "red") {
console.log(color);
} else if (color == "purple") {
if (5 > 6) {
console.log("First nested if-statement was true");
} else {
console.log("First nested if-statement was false");
}
}
See the Pen Exercise 3.1 by LSU DDEM (@lsuddem) on CodePen.