function printAnimals(animal) {
if (animal === "dog" || animal === "cat") {
console.log(`I have a ${animal}`);
}
}
console.log(printAnimals("dog")); // I have a dog
function printAnimals(animal) {
const animals = ["dog", "cat", "hamster", "turtle"];
if (animals.includes(animal)) {
console.log(`I have a ${animal}`);
}
}
console.log(printAnimals("hamster")); // I have a hamster
const printAnimalDetails = (animal) => {
let result; // declare a variable to store the final value
// condition 1: check if animal has a value
if (animal) {
// condition 2: check if animal has a type property
if (animal.type) {
// condition 3: check if animal has a name property
if (animal.name) {
// condition 4: check if animal has a gender property
if (animal.gender) {
result = `${animal.name} is a ${animal.gender} ${animal.type};`;
} else {
result = "No animal gender";
}
} else {
result = "No animal name";
}
} else {
result = "No animal type";
}
} else {
result = "No animal";
}
return result;
};
console.log(printAnimalDetails()); // 'No animal'
console.log(printAnimalDetails({ type: "dog", gender: "female" })); // 'No animal name'
console.log(printAnimalDetails({ type: "dog", name: "Lucy" })); // 'No animal gender'
console.log(
printAnimalDetails({ type: "dog", name: "Lucy", gender: "female" })
); // 'Lucy is a female dog'
const printAnimalDetails = ({ type, name, gender } = {}) => {
if (!type) return "No animal type";
if (!name) return "No animal name";
if (!gender) return "No animal gender";
// Now in this line of code, we're sure that we have an animal with all //the three properties here.
return `${name} is a ${gender} ${type}`;
};
console.log(printAnimalDetails()); // 'No animal type'
console.log(printAnimalDetails({ type: dog })); // 'No animal name'
console.log(printAnimalDetails({ type: dog, gender: female })); // 'No animal name'
console.log(printAnimalDetails({ type: dog, name: "Lucy", gender: "female" })); // 'Lucy is a female dog'
function printVegetablesWithQuantity(vegetable, quantity) {
const vegetables = ["potato", "cabbage", "cauliflower", "asparagus"];
// condition 1: vegetable should be present
if (vegetable) {
// condition 2: must be one of the item from the list
if (vegetables.includes(vegetable)) {
console.log(`I like ${vegetable}`);
// condition 3: must be large quantity
if (quantity >= 10) {
console.log("I have bought a large quantity");
}
}
} else {
throw new Error("No vegetable from the list!");
}
}
printVegetablesWithQuantity(null); // No vegetable from the list!
printVegetablesWithQuantity("cabbage"); // I like cabbage
printVegetablesWithQuantity("cabbage", 20);
// 'I like cabbage`
// 'I have bought a large quantity'
现在,我们有:
过滤无效条件的 if/else 语句
3 层嵌套的 if 语句(条件 1、2 和 3)
一个通用的规则是当发现无效条件时尽早返回。
function printVegetablesWithQuantity(vegetable, quantity) {
const vegetables = ["potato", "cabbage", "cauliflower", "asparagus"];
// condition 1: throw error early
if (!vegetable) throw new Error("No vegetable from the list!");
// condition 2: must be in the list
if (vegetables.includes(vegetable)) {
console.log(`I like ${vegetable}`);
// condition 3: must be a large quantity
if (quantity >= 10) {
console.log("I have bought a large quantity");
}
}
}
function printVegetablesWithQuantity(vegetable, quantity) {
const vegetables = ["potato", "cabbage", "cauliflower", "asparagus"];
if (!vegetable) throw new Error("No vegetable from the list!");
// condition 1: throw error early
if (!vegetables.includes(vegetable)) return;
// condition 2: return from the function is the vegetable is not in
// the list
console.log(`I like ${vegetable}`);
// condition 3: must be a large quantity
if (quantity >= 10) {
console.log("I have bought a large quantity");
}
}
function printFruits(color) {
// use switch case to find fruits by color
switch (color) {
case "red":
return ["apple", "strawberry"];
case "yellow":
return ["banana", "pineapple"];
case "purple":
return ["grape", "plum"];
default:
return [];
}
}
printFruits(null); // []
printFruits("yellow"); // ['banana', 'pineapple']
上面的代码实现没有错误,但是很冗长,同样的结果可以使用更简洁的语法来实现。
// use object literal to find fruits by color
const fruitColor = {
red: ["apple", "strawberry"],
yellow: ["banana", "pineapple"],
purple: ["grape", "plum"],
};
function printFruits(color) {
return fruitColor[color] || [];
}
同样的,也可以使用 Map 来实现:
// use Map to find fruits by color
const fruitColor = new Map()
.set("red", ["apple", "strawberry"])
.set("yellow", ["banana", "pineapple"])
.set("purple", ["grape", "plum"]);
function printFruits(color) {
return fruitColor.get(color) || [];
}
function printVegetablesWithQuantity(vegetable, quantity = 1) {
// if quantity has no value, assign 1
if (!vegetable) return;
console.log(`We have ${quantity} ${vegetable}!`);
}
//results
}
printVegetablesWithQuantity('cabbage'); // We have 1 cabbage!
printVegetablesWithQuantity('potato', 2); // We have 2 potato!
// destructing - get name property only
// assign default empty object {}
function printVegetableName({ name } = {}) {
console.log(name || "unknown");
}
printVegetableName(undefined); // unknown
printVegetableName({}); // unknown
printVegetableName({ name: "cabbage", quantity: 2 }); // cabbage
因为我们只需要属性名,所以我们可以使用 {name} 来改变参数的结构,然后我们可以在代码中使用 name 作为变量,而不是使用 vegetable.name。
我们还将一个空对象 {} 赋值为默认值,否则在执行 printVegetableName(undefined) 时,它将给出一个错误—— Cannot destructure property name of undefined or null,因为在 undefined 中没有 name 属性。
// to get the car model
const model = car?.model ?? "default model";
// to get the manufacturer street
const street = car?.manufacturer?.address?.street ?? "default street";
// to check if the car manufacturer is from the USA
const isManufacturerFromUSA = () => {
if (car?.manufacturer?.address?.state === "USA") {
console.log("true");
}
};