Ternary Conditionals
isArthur && isKing ?
(weapon = "Excalibur", helmet = "Goosewhite") :
isArcher ? (weapon = "Longbow", helmet = "Mail Helm") :
(weapon = "Longsword", helmet = "Iron Helm");;
The “OR” Operator
- When used in assignment, the OR operator will try to select the first value it encounters that is not “false”.
- The OR operator takes the leftmost “truth” value, and if none exists, the last “false” value.
var result1 = undefined || 42;
console.log(result1); // 42
var result2 = 0 || ["Item1", "Item2"];
console.log(result2); // ["Item1", "Item2"]
var result3 = "" || {type: "Type", item: "Item"};
console.log(result3); // {type: "Type", item: "Item"}
When all elements are “true”, the FIRST “true” value assigned.
var result1 = "Value" || "Item"; console.log(result1); // "Value"
When all elements are “false”, the LAST “false” value assigned.
var result1 = undefined || ""; console.log(result1); // ""
The “AND” Operator
- The && operator takes the rightmost “truth” value or the first “false” value.
var result1 = undefined && 42;
console.log(result1); // undefined
var result2 = 0 && ["Item1", "Item2"];
console.log(result2); // 0
var result3 = "" && {type: "Type", item: "Item"};
console.log(result3); // ""
When all elements are “true”, && will return the LAST “true” value found.
var result1 = "Value" && "Item"; console.log(result1); // "Item"
The Switch Block
function Knight (name, regiment){
this.name = name;
this.regiment = regiment;
switch (regiment) {
case 1:
this.weapon = "Broadsword";
break;
case 2:
this.weapon = "Claymore";
break;
case 3:
this.weapon = "Longsword";
break;
case 5:
this.weapon = "War Hammer";
break;
case 6:
this.weapon = "Battle Axe";
break;
case 4:
case 7:
case 8:
this.weapon = "Morning Star";
break;
case "King":"
this.weapon = "Excalibur";
break;
default:
alert(name + " has an incorrect " + "
"regiment, Master Armourer!" + "
"\n\nNo weapon assigned!");
A carefully organized switch block can add LEAST common properties first and MOST common, last.
function ceremonialDagger(knight, rank){
this.length = 8;
this.owner = knight;
switch(rank){
case "King": this.diamonds = 1;
case "High Constable": this.amethyst = 2;
case "Field Marshal": this.sapphires = 4;
case "Captain": this.emeralds = 1;
case "Knight": this.rubies = 6;
}
}
var marshalsDagger = new ceremonialDagger("Timothy", "Field Marshal");
console.log(marshalsDagger); // ceremonialDagger {length: 8, owner: "Timothy", sapphires: 4, emeralds: 1, rubies: 6}