Upgrade to Pro — share decks privately, control downloads, hide ads and more …

IF ... THEN ... ELSE

IF ... THEN ... ELSE

4 tips for write cleaner code

Nicola Sanitate

October 24, 2018
Tweet

More Decks by Nicola Sanitate

Other Decks in Programming

Transcript

  1. function test(fruit) { if (fruit == 'apple' || fruit ==

    'strawberry') console.log('red'); }
  2. function test(fruit, quantity) { const redFruits = ['apple', 'strawberry', 'cherry',

    'cranberries']; if (fruit) { if (redFruits.includes(fruit)) { console.log('red'); if (quantity > 10) console.log('big quantity'); } } else { throw new Error('No fruit!'); } }
  3. function test(fruit, quantity) { const redFruits = ['apple', 'strawberry', 'cherry',

    'cranberries']; if (!fruit) throw new Error('No fruit!'); if (!redFruits.includes(fruit)) return; console.log('red'); if (quantity > 10) console.log('big quantity'); }
  4. function test(color) { switch (color) { case 'red': return ['apple',

    'strawberry']; case 'yellow': return ['banana', 'pineapple']; case 'purple': return ['grape', 'plum']; default: return []; } }
  5. const fruitColor = { red: ['apple', 'strawberry'], yellow: ['banana', 'pineapple'],

    purple: ['grape', 'plum'] }; function test(color) { return fruitColor[color] || []; }
  6. const fruits = [ { name: 'apple', color: 'red' },

    { name: 'banana', color: 'yellow' } ]; function test() { let isAllRed = true; for (let f of fruits) { if (f.color == 'red') { isAllRed = false; break; } } console.log(isAllRed); }
  7. const fruits = [ { name: 'apple', color: 'red' },

    { name: 'banana', color: 'yellow' } ]; function test() { const isAllRed = fruits.every(f => f.color == 'red'); console.log(isAllRed); }