자바스크립트 트릭 모음

실무에서 쓸 수 있는 자바스크립트 트릭 모음입니다.

삼항연산자

Bad
let hungry = true;
let eat; 
if (hungry === true) {
    eat = 'yes'; 
} else {
    eat = 'no';
}
Good
let hungry = true;
let eat = hungry === true ? 'yes' : 'no';

형변환

Bad
let num = 15; 
let s = num.toString(); // number to string
let n = Number(s); // string to number
Good
let num = 15;
let s = num + ""; // number to string
let n = +s; // string to number

배열 채우기

Bad
let arraySize = 10;
let filledArray = [];
for(let i=0; i < arraySize; i++){
    filledArray[i] = {'hello' : 'goodbye'};
}
// [{hello:'goodbye'},{hello:'goodbye'},{hello:'goodbye'}...]
Good
let arraySize = 10;
let filledArray = new Array(arraysize).fill(null).map(()=> ({'hello' : 'goodbye'}));
// [{hello:'goodbye'},{hello:'goodbye'},{hello:'goodbye'}...]

객체 속성 추가

Bad
let dynamic = "value";
let user = {
    id : 1;
};
user[dynamic] = "other value";
Good
let dynamic = "value";
let user = {
    id : 1,
    [dynamic] : "other value"
}

배열의 중복 요소 제거

Bad
let array = [100, 23, 23, 23, 23, 67, 45]; 
let outputArray = [];
let flag = false; 
for (j = 0; < array.length; j++) {
    for (k = 0; k < outputArray.length; k++) {
        if (array[j] == outputArray[k]) {
            flag = true;
        }
    }
    if (flag == false) {
        outputArray.push(array[j]);
    }
    flag = false;
}
//outputArray = [100, 23, 67, 45]
Good
let array = [100, 23, 23, 23, 23, 67, 45]; 
let outputArray = Array.from(new Set(array));
//outputArray = [100, 23, 67, 45]

Array to Object

Bad
let arr = ["value1", "value2", "value3"]; 
let arrObject = {};
for (let i = 0; i < arr.length; ++i) {
    if (arr[i] !== undefined) {
        arrObject[i] = arr[i];
    }
}
/*
{
    "0": "value1",
    "1": "value2",
    "2": "value3"
}
*/
Good
let arr = ["value1", "value2", "value3"];
let arrObject = {...arr};
/*
{
    "0": "value1",
    "1": "value2",
    "2": "value3"
}
*/

Object to Array

Bad
let number = {
    one: 1, 
    two: 2,
};
let keys = []; 
for (let numbers in number) {
    if (number.hasOwnProperty(numbers)) {
        keys.push(numbers);
    }
}
// ["one","two"]
Good
let numbers = {
    one: 1,
    two: 2,
};
let key = Object.keys(numbers); // key = [ 'one', 'two' ]
let value = Object.values(numbers);  // value = [ 1, 2 ]
let entry = Object.entries(numbers); // entry = [['one' : 1], ['two' : 2]]

짧은 조건문

Bad
if (doc) {
    goToDocs();
}
Good
doc && goToDocs();

const a = 0;
const zeroEqualFalse = a || false; // false
const zeroValuable  = a && false; // 0

숫자 비교(not)

Bad
let a = 123;
if (a != 123) {
    // context
}
Good
let a = 123;
if (a^1234) {
    console.log('false');
}
// false

객체 반복문

const age = {
    Rahul : 20,
    max : 16
}

// Solution 1
const keys = Object.keys(age); // ['Rahul','Max']
keys.forEach(key => age[key]++);
console.log(age);

// Solution 2
for(let key in age) {
    age[key]++;
}
console.log(age);
// {Rahul :20, max : 16}

객체 키 불러오기

const obj = {
    name : "Rahul",
    age : 16,
    address : "Earth",
    profession : "Developer"
};
console.log(Object.keys(obj));
// [name, age, address, profession]

배열 여부 체크

const arr = [1,2,3];

console.log(typeof arr); // object
console.log(Array.isArray(arr)); // true

배열 기본값으로 채우기

const size = 5;
const defaultValue = 0;
const arr = Array(size).fill(defaultValue);
console.log(arr); // [0,0,0,0,0]

함수에 매개변수 전달

function downloadData(url, resourceId, searchText, pageNo) {}
downloadData(...);  // 매개변수 순서를 알고 있어야 함
function downloadData(
   { url, resourceId, searchText, pageNo } = {}
) {}

downloadData({
    resourceId : 2,
    url : "/posts",
    searchText : 'Test'
})