대빵's Blog

자바스크립트 코드 개선 기술 본문

개발관련

자바스크립트 코드 개선 기술

bigzero 2021. 8. 10. 10:49
Tenary Operator (삼항연산자)

```
///////////////// 삼항연산자 //////////////
// bad code
function getResult1(score) {
  let result;
  if (score > 5) {
    result = '👍';
  } else {
    result = '👎';
  }
  return result;
}

// good code
function getResult2(score) {
  return score > 5 ? '👍' : '👎';
}

console.log(getResult1(5));
console.log(getResult2(5));
```


Nullish Coalescing Operator

```
///////////////// Nullish Coalescing Operator //////////////
// bad code
function printMessage1(text) {
  let message = text;
  if (text == null || text == undefined) {
    message = 'Nothing to display';
  }
  console.log(message);
}

// good code
function printMessage2(text) {
  const message = text ?? 'Nothing to display'
  console.log(message);
}

// cf : default parameter 를 사용하는 경우 null 처리가 안됨.
function printMessage3(text = 'Nothing to display') {
  console.log(text);
}

// cf : logical OR Operator => leftExpr(falsy) || rightExpr
function printMessage4(text) {
  // falsy => false, 0, -0, NaN, undefined, null, '', "", ``
  const message = text || 'Nothing to display'
  console.log(message);
}

/*
  const result = getInitialState() ?? fetchFromServer();
  console.log(result);

  function getInitialState() {
    return null;
  }

  function fetchFromServer() {
    return 'Hiya from ';
  }
*/

printMessage2('Hello');
printMessage2(undefined);
printMessage2(null);

printMessage3('Hello');
printMessage3(undefined);
printMessage3(null);

printMessage4('Hello');
printMessage4(undefined);
printMessage4(null);
printMessage4(0);
printMessage4('');
```


Object Destructuring

```
// Object Destructuring
const person = {
  name: 'Julia',
  age: 30,
  phone: '01077777777'
};

// bad code
function displayPerson(person) {
  displayAvatar(person.name);
  displayName(person.name);
  displayProfile(person.name, person.age);
}

// good code
function displayPerson(person) {
  const { name, age } = person;
  displayAvatar(name);
  displayName(name);
  displayProfile(name, age);
}
```


Object & Array Spread 

```
// Spread object and array
const item = { type: '👔', size: 'M' };
const detail = { price: 20, made: 'Korea', gender: 'M' };

// bad code
const newObject = new Object();
newObject['type'] = item.type;
newObject['size'] = item.size;
newObject['price'] = item.price;
newObject['made'] = item.made;
newObject['gender'] = item.gender;

// good code
const shirt0 = Object.assign(item, detail);

const shirt = { ...item, ...detail };
const shirt = { ...item, ...detail, price: 40 };  // deatil 의 price 만 40 으로 변경

// spread syntax - array
let fruites = ['🍉', '🍊', '🍌']
// fruits.push('🍓')
fruits = [...fruites, '🍓']
// fruits.unshift('🍇')
fruits = ['🍇', ...fruites]

const fruits2 = ['🍉', '🍊', '🍌'];
let combined = fruits.concat(fruits2);
combined = [...fruits, ... fruits2];
```


Optional Chaining

```
// Optional chaining
const bob = {
  name: 'Julia',
  age: 20,
};
const anna = {
  name: 'Julia',
  age: 20,
  job: {
    title: 'Software Engineer'
  },
};

// bad code
function displayJobTitle(person) {
  if (person.job && person.job.title) {
    console.log(person.job.title);
  }
}

// good code
function displayJobTitle(person) {
  if (person.job?.title) {
    console.log(person.job.title);
  }
}

function displayJobTitle(person) {
  const title = persion.job?.title ?? 'No Job Yet';
  console.log(title);
}
```


Template literals

```
// Template Literals (Template String)
const person = {
  name: 'Julia',
  score: 4,
};

// bad code
console.log ( 'Hello' + person.name + ', Your current score is:' + person.score);

// good code
console.log(`Hello ${person.name}, Your current score is: ${person.score}`);

// good code
const { name, score } = person;
console.log(`Hello ${name}, Your current score is: ${score}`);

// good code
function greetings(person) {
  const { name, score } = person;
  console.log(`Hello ${name}, Your current score is: ${score}`);
}
```


Loops

```
// Looping - Q : 짝수들만 각각 4를 곱한 전체합
const items = [1,2,3,4,5,6]

// bad code
const evens = getAllEvens(items);
const multiple = multiplyByFour(evens);
const sum = sumArray(multiple);
console.log(sum);

function getAllEvens(items) {
  const result = [];
  for (let i=0, j=items.length ; i<j ; i++) {
    if (items[i] % 2 === 0) {
      result.push(items[i]);
    }
  }
  return result;
}

function multiplyByFour(items) {
  const result = [];
  for (let i=0, j=items.length ; i<j ; i++) {
    result.push(items[i] * 4);
  }
  return result;
}

function sumArray(items) {
  let sum = 0;
  for (let i=0 , j=items.length ; i<j ; i++) {
    sum += items[i];
  }
  return sum;
}

// good code
function getAllEvens(items) {
  return items.filter(num => num % 2 === 0);
}

function multiplyByFour(items) {
  return items.map(num => num * 4);
}

function sumArray(items) {
  return items.reduce((a, b) => a + b, 0);
}

// good code final 1
const evens = items.filter((num) => num % 2 === 0);
const multiple = evens.map((num) => num * 4);
const sum = multiple.reduce((a,b) => a + b, 0);
console.log(sum);

// good code final 2
const result = items
  .filter((num) => num % 2 === 0)
  .map((num) => num * 4)
  .reduce((a,b) => a + b, 0);
console.log(result);
```


Async (promise 대체)

```
// Promise -> Async/await

// bad code
function displayUser() {
  fetchUser()
    .then((user) => {
      fetchProfile(user)
        .then((profile) => {
          updateUI(user, profile);
        });
    });
}

// good code
async function displayUser() {
  const user = await fetchUser();
  const profile = await fetchProfile(user);
  updateUI(user, profile);
}
```


Remove Duplicate 방법

```
// Remove Duplicates
const array = ['🐶', '🐱', '🐂', '🐱', '🐈', '🐶']
console.log(array);

// 중복제거
console.log([...new Set(array)]);
```