Skip to content

Instantly share code, notes, and snippets.

@zduymz
Created October 8, 2018 20:16
Show Gist options
  • Save zduymz/2dfa11d650697860d6b015854d771976 to your computer and use it in GitHub Desktop.
Save zduymz/2dfa11d650697860d6b015854d771976 to your computer and use it in GitHub Desktop.
Javascript notes

Javascript Note

Debug

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

console.table([foo, bar, baz])

Destructing

const turtle = {
    name: 'Bob',
    legs: 4,
    shell: true,
    meal: 10
}

function feed({name, meal}) {
    return `Feed ${name} ${meal}`
}
// OR
function feed(animal) {
    const {name, meal} = animal;
    return `Feed ${name} $meal`
}

Template litterals

const horse = {
    name: 'Topher',
    size: 'large',
    skills: ['jousting', 'racing'],
    age: 7
}
const {name, size, skills} = horse;
bio = `${name} is a ${size} horse skilled in ${skills.join(' & ')}`

Advanced Tag

function horseAge(str, age) {
    const ageStr = age > 5? 'old': 'young';
    return `${str[0]}${ageStr} at ${age} years`
}
const bio2 = horseAge`This horse is ${horse.age}`

Spread syntax

const pikachu = {name: 'Pikachu'};
const stats = {hp: 40, attack: 60, defense: 45};

// Bad Object code
pikachu['hp'] = stats.hp;
pikachu['attack'] = stats.attack;
pikachu['defense'] = stats.defense;
//OR
const lv10 = Object.assign(pikachu, stats);
const lv11 = Object.assign(pikachu, {hp: 45});

// Good Object code
const lv10 = {...pikachu, ...stats};
const lv11 = {...pikachu, hp: 45};

Loops

orders = [10,2,8,11,9];
//Reduce
const total = orders.reduce((acc, cur) => acc + cur);
//Map
const withTax = orders.map(v => v * 1.1);
//Filter
const highValue = orders.filter(v => v > 100);

Async/Await

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

const sumRandomAsyncNums = async() => {
    const first = await random();
    const second = await random();
    const third = await random();
    console.log(`Result ${first + second + third}`)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment