Decisions and branching logic
There are a nuumber of mechanisms to evaluate criteria and choose what to do. // being that you dont want to assign a new value to your test variable, use the double == or tripple === as comparison operators,
If-then-else
If condition true do something else do something else
// prints 1
let myChoice = 1;
if (myChoice == 0){
console.log("You chose 0");
}
else if (myChoice == 1){
console.log("You chose 1");
}
else {
console.log("You chose something weird");
};
Switch statement
if condition matches an option do something specific else do a default operation
// switch - prints "You chose 1"
myChoice = 1
switch (myChoice) {
case 0:
console.log("You chose 0");
break;
case 1:
console.log("You chose 1");
break;
default:
console.log("You chose something weird");
break;
}
Ternary operator
If true do this, else that. (three parts) - condition ? true part : false part
let age = 19;
let text = (age < 18) ? "Minor" : "Adult";
console.log("Ternary: " + text); // Will return 'Ternary: Adult'
Logical OR
Return true bit or false bit. (returnedValue = thisIfTrue OR otherwiseThis)
let firstPort;
let secondPort = 9999;
let port = firstPort || 3000;
console.log(port); // defaults to 3000 as firstPort is not initialised
port = secondPort || 3000;
console.log(port); // uses 9999 as secondPort value initialised.
Nulish coalesence
If a variable is null or undefined, return it, otherwise return something else. ( varToTest ?? returnThisIfFalse)
let r;
const q = "cat";
console.log( r ?? "dog"); // prints dog because r is null or undefined
console.log( q ?? "dog"); // prints cat as variable already initialised
Optional Chaining
Return ‘undefined’ if a higher-level object is not present, rather than error. (?)
let person = {
name: 'Fred',
email: 'fred.flintstone@quarry.com'
}
console.log(person.avatar?.url); // If avatar property undefined, dont get url, just return undefined