arlyxiao / best-practice

1 stars 0 forks source link

javascript 技巧 - 保持简洁写法 #63

Open arlyxiao opened 3 years ago

arlyxiao commented 3 years ago

Null, Undefined, Empty checks

if(productName !== undefined || productName !== "" || productName !== null){
    console.log(productName)
}

// Shorthand version
if(productName){
    console.log(productName)
}

Multiple conditions

//longhand
if (x === 'orange' || x === 'red' || x === 'gray') {
    // do something
}

//shorthand
if (['orange', 'red', 'gray'].includes(x)) {
    // do something
}

Loops

//longhand
for (var i = 0; i < productsList.length; i++){
    // do things
}

//shorthand (to access the index)
for (let i in productsList){
    // do things
}
// or (to access productsList's elements)
for (let i of productsList){
    // do things
}

// or with foreach
productsList.forEach(element => {
    // do things
});

Implicit return

//longhand
function getProductPrice() {
    return quantity * productPrice;
}

//shorthand 
getProductPrice = price => quantity * productPrice;

Spread operator

const team = ['John', 'Adam', 'Yan'];

//longhand 
//- joining
const group = ['Sam', 'Chris', 'Sarah'].concat(team);
//- cloning
const newGroup = team.slice();

//shorthand 
//- joining
const group = ['Sam', 'Chris', 'Sarah', ...team];
//- cloning
const newGroup = [...team];

Arrow function

//longhand
function welcomeMessage(name) {
    console.log('Welcome ', name);
}

//shorthand
welcomeMessage = name => console.log(name);

Template literal


// longhand
const winnerMsg = 'Congrats to the winner: ' + winnerName + ', you got a ' + gift;

// shorthand
const winnerMsg = `Congrats to the winner: ${winnerName}, you got a ${gift}`;

Multiple lines

// Longhand
const msg = 'Working in conjunction with humanitarian aid agencies,\n\t'
    + 'we have supported programmes to help alleviate human suffering. \n\t';

//Shorthand
const msg = `Working in conjunction with humanitarian aid agencies,
we have supported programmes to help alleviate human suffering.`;

Array.find

//Longhand
const animals = [
    { name: 'octopus', animalClass: 'invertebrates' },
    { name: 'shark', animalClass: 'fish' },
    { name: 'toad', animalClass: 'amphibians' },
    { name: 'snake', animalClass: 'reptiles' }
];

function findReptile(name){
    for(let i=0; i < animals.length; ++i){
        if(animals[i].animalClass === 'reptiles' && animals[i].name === name){
        return animals[i]
        }
    }
}

// Shorthand
findReptile = name => (
    animals.find(animal => animal.animalClass ==='reptiles' && animal.name === name)
) 

https://levelup.gitconnected.com/9-tricks-for-writing-short-and-smart-javascript-code-6c832290e0b1

保持代码好习惯