В этой статье я хотел бы дать хорошее и современное решение некоторой проблемы.

Пойдем.

Отладка

Например, у нас есть 3 объекта

const foo = {
    name: 'this is object foo',
};
const bar = {
    name: 'this is object bar',
};
const baz = {
    name: 'this is object baz',
};

Как вы можете получить отладку

Плохой код

console.log(foo);
console.log(bar);
console.log(baz);

Хороший код

console.log({foo, bar, baz});

  • Бонус

Хороший код

function Person(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
}
var family = {};
family.mother = new Person("Jane", "Smith");
family.father = new Person("John", "Smith");
family.daughter = new Person("Emily", "Smith");
console.table(family);

Очень хорошо прочитано. не так ли?

Мы также можем указать ваш собственный стиль в консоли, например, сообщение в консоли, когда мы открываем его на странице facebook.

Вот как это делается

var cssRule =
    "color: rgb(189, 7, 7);" +
    "font-size: 60px;" +
    "font-weight: bold;" +
    "text-shadow: 1px 1px 5px rgb(103, 0, 0);" +
    "filter: dropshadow(color=rgb(249, 162, 34), offx=1, offy=1);";
console.log("%cStop!", cssRule);
  • Бонус
function foo() {
  function bar() {
    console.trace('i am here');
  }
  bar();
}
foo();

Здесь мы можем увидеть все звонки до console.trace

Спред

Например, у нас есть эти объекты

const student = { name: 'Poxos', age: 19}
const info = { iq: 120, country: 'Yerevan' }

Как мы можем связать ученицу и ее информацию

Плохой код

student['country'] = info.country;
student['iq'] = info.iq;

Or

const newStudent = Object.assign(student, info);

Хороший код

const newStudent = {...student, ...info}

Нажать / отменить сдвиг

const arr = [ 2, 3, 4 ];

Плохой код

arr.push(5);
arr.push(6);
arr.push(7);

Хороший код

arr = [ ...arr, 4, 5, 6 ]; 
///unshift
arr = [ 0, 1, ...arr ];

Удалить элемент.

const arr = { title: 'title', info: 'info' };

Плохой код

delete arr.info;

Хороший код

const {
    info,
    ...newObject
} = arr;
arr = newObject,

Петли

const orders = [ 123, 22, 8, 400, 32 ]

Плохой код

const total = 0;
const withTax = [];
const highValue = [];
for (i = 0; i < orders.length; ++i) {
    //reduce
    total += orders[i];
    //map
    withTax.push(orders[i] * 1.1);
    //filter
    if(orders[i] > 100) {
        highValue.push(orders[i]);
    }
}

Хороший код

const total = orders.reduce((acc, cur) => acc + cur);
const withTax = orders.map(v => v * 1.1);
const highValue = orders.filter(v => v > 100);

Асинхронное ожидание

const random = () => {
    return Promise.resolve(Math.random())
}

Плохой код

const sumRandomAsyncNums = () => {
        let first;
        let second;
        let third;
        return random()
            .then(v => {
                first = v;
                return random();
            })
            .then(v => {
                second = v;
                return random();
            })
            .then(v => {
                third = v;
                return ` ${first} ${second} ${third}`;
            })
            .then(v => {
                console.log(`Result ${v}`);
            })
    }

Хороший код

const sumRandomAsyncNums = async() => {
        const first = await random();
        const second = await random();
        const third = await random();
        console.log(`Result ${first} ${second} ${third}`);
    }

Хороший код

++

const sumRandomAsyncNums = async() => {
        const randos = Promise.all([random(), random(), random()]);
        let result = 0;
        for(const r of await randos) {
            result += r;
        }
        console.log(`Result ${result}`);
    }

Обратные вызовы

Например, у нас есть один магазин в вашем родительском компоненте. И это свойства good и bad, и у нас есть 2 дочерних компонента.

class Parent extends React.Component {
    this.state = {
        bad: [],
        good: [],
    }
    <Child
    />
    <Child
    />
}
function Child(props) {
    addItem() {
        return Math.random();
    }
}

Как вы можете создать свою функцию обратной связи для добавления bad или good реквизитов.

Плохой код

class Parent extends React.Component {
    this.state = {
        bad: [],
        good: [],
    }
    const addItemByType = (type, item) {
        this.setState({[type]: [...this.state[type], item]});
    }
    <Child
        type='bad'
        addItemByType={this.addItemByType}
    />
    <Child
        type='good'
        addItemByType={this.addItemByType}
    />
}
function Child(props) {
    addItem() {
        return props.addItemByType(props.type, Math.random())
    }
}

Хороший код

class Parent extends React.Component {
    this.state = {
        bad: [],
        good: [],
    }
    const addItemByType = type => item => {
        this.setState({[type]: [...this.state[type], item]});
    }
    <Child
        addItemByType={this.addItemByType('bad')}
    />
    <Child
        addItemByType={this.addItemByType('good')}
    />
}
function Child(props) {
    addItem() {
        return props.addItemByType(Math.random())
    }
}