A simple conditional can be constructed with the if method:
if(condition) {
// code
}When doing equality comparisons, JS supports both double(==) and triple (===) conditionals. The double equality symbol does not match data types, only values.
const x = 10;
const y = "10";
if(x == 10) {
console.log("x is 10")
}
if(x == y) {
console.log("matches value")
}
if(x === 10) {
console.log("matches value AND type")
}
if(x === y) {
console.log("this will not print")
} else if(x === "10") {
console.log("will also not print")
} else {
console.log("data type and value don't match")
}We can also do multiple conditionals with logical or/and:
const x = 4;
const y = 10;
if(x > 5 || y > 10){ // Logical OR
// rest of code
}
if(x > 5 && y > 10){ // Logical AND
// rest of code
}Info
Single pipe
|or ampersand&is the bitwise operator, rather than logical
Ternary operator (if true then this else that)
There is also a ternary operator, then, which is represented by a question mark ? and else, represented by a colon : . In this example, if x > 10 then(?) assign "red", else(:) assign "blue"
// Ternary operator
const t = 10;
// if condition THEN (?) value, ELSE (:) other value
const color = x > 10 ? "red" : "blue";
console.log(color)Switches
The basic syntax for switches is as follows:
switch(color) {
case "red":
console.log(`color is ${color}`);
break;
case "blue":
console.log(`color is ${color}`);
break;
default:
console.log(`color is unknown.`);
}The break is required because otherwise the default case will run even if a specific case is matched.