function transformData(rawData) { // check if no data if (!rawData) { return []; } // actual function code goes here return rawData.map((item) => item); }
將無效的用例儘早返回,避免意外和沒必要要的代碼處理。javascript
function getDrink (type) { if (type === 'coke') { type = 'Coke'; } else if (type === 'pepsi') { type = 'Pepsi'; } else if (type === 'lemonade') { type = 'Lemonade'; } else if (type === 'fanta') { type = 'Fanta'; } else { // acts as our "default" type = 'Unknown drink!'; } return 'You\'ve picked a ' + type; } // Object literal function getDrink (type) { var drinks = { 'coke': 'Coke', 'pepsi': 'Pepsi', 'lemonade': 'Lemonade', 'default': 'Default item' }; return 'The drink I chose was ' + (drinks[type] || drinks['default']); }
function testFun(fruit) { if (fruit == 'apple' || fruit == 'strawberry' || fruit === 'cherry') { console.log('red'); } } // ----- 改進後 ------ function testFun(fruit) { const fruits = ['apple', 'strawberry', 'cherry']; if (redFruits.includes(fruit)) { console.log('red'); } // if (!~redFruits.indexOf(fruit)) { // console.log('red'); // } }
const exampleValues = [2, 15, 8, 23, 1, 32]; const [truthyValues, falseyValues] = exampleValues.reduce((arrays, exampleValue) => { if (exampleValue > 10) { arrays[0].push(exampleValue); return arrays; } arrays[1].push(exampleValue); return arrays; }, [[], []]);