Byte becomes a bouncer
How a program makes decisions: comparisons, if, else if, && and ||, the remainder % and switch.
if for exactly that.Comparisons first. They answer a yes-or-no question and give true or false:
a > b,a < b,a >= b,a <= b;a === b— equal;a !== b— not equal.
console.log(5 > 3);
console.log(2 === 2);
console.log("cat" !== "dog");
console.log(10 <= 9);Now if. The code in curly braces runs only if the condition is true. And else is plan B, for when the condition is false.
function bouncer(age) {
if (age >= 18) {
return "Come on in!";
} else {
return "Go home, kitten";
}
}
console.log(bouncer(25));
console.log(bouncer(12));More than two options? An else if chain checks the conditions one by one, top to bottom, and stops at the first one that fits.
function dressCode(outfit) {
if (outfit === "tuxedo") {
return "VIP area";
} else if (outfit === "pyjamas") {
return "Pyjama party only";
} else {
return "Dance floor";
}
}
console.log(dressCode("pyjamas"));
console.log(dressCode("hoodie"));console.log("5" == 5);
console.log("5" === 5);
console.log(0 == "");Conditions can be combined: && means “and” (both needed), || means “or” (one is enough), ! means “not”.
const age = 20;
const hasTicket = false;
console.log(age >= 18 && hasTicket);
console.log(age >= 18 || hasTicket);
console.log(!hasTicket);One more operator comes in handy at the door: %, the remainder of a division. 7 % 2 is 1: seven cats paired up, and one is left without a partner. If the remainder of dividing by 2 is zero, the number is even.
console.log(7 % 2);
console.log(10 % 2);
console.log(10 % 3);
function isEven(n) {
return n % 2 === 0;
}
console.log(isEven(4), isEven(7));% answers “does it divide evenly?” — a remainder of 0 means yes.When one value is compared against a whole list of options, an else if chain gets long. That's what switch is for: it takes a value and looks for a case with the same one. No match — it goes to default.
function welcomeDrink(guest) {
switch (guest) {
case "cat":
return "milk";
case "dog":
return "a bone in a glass";
default:
return "water";
}
}
console.log(welcomeDrink("cat"));
console.log(welcomeDrink("hamster"));function coffee(size) {
let text = "";
switch (size) {
case "large":
text = text + "double ";
case "small":
text = text + "coffee";
break;
default:
text = "water";
}
return text;
}
console.log(coffee("large"));
console.log(coffee("small"));break, so it fell through into “small”. Here that's intended — when it isn't, it's a bug.true or false. Instead of if (x > 0) { return true; } else { return false; } just write return x > 0;. Less code, more nap time.Pop quiz
Mistakes are fine: keep trying until you find the right answer, and Byte explains why it's right.