/ FRONTEND

클린코드 자바스크립트 1-2 변수 다루기(전역 공간 사용 최소화,임시 변수 제거하기)

Clean Code JS 강좌는 여러 절로 구성되어 있습니다.

변수 다루기 😎

전역 공간 사용 최소화 👍

누구에게 들어보았나요?

  1. 경험
  2. 누군가 혹은 자바스크립트 생태계
  3. 강의 혹은 책
  4. 회사 혹은 책
  5. Lint

전역 (최상위)

  • Window (Web Browser)
  • global (NodeJS)

ex) index.js 와 index2.js를 웹이 같이 불러올 때,

  • 아래와 같이, setTimeout 에러 없이 동작 불가
  • Web API이기 때문에 에러가 나오지 않는다.
// index.js)

var globalVar = 'global';
console.log(globalVar);
console.log(window.globalVar);

var setTimeout = 'setTimeout';
// 에러 없이 동작 불가,
// Web API이기 때문에 에러가 나오지 않는다.

function setTimeout() {
    console.log('function)
}

// index2.js)

console.log(globalVar) // 사용 가능

setTimeout(() =>{
console.log('1')};
,1000);
  • index 라는 전역 변수가 남는다.
  • let 이나 const 로 바꾸어주어야함
for (var index = 0; index < array.length; index++) {
  const element = array[index];
}
//

전역 공간을 더럽히면 왜 안될까?🤦‍♂️

  • 어디서나 접근 가능하다.
  • 스코프 분리 위험 (사람이 생각하기에 분리했지만 런타임 환경에서는 분리하지 못했다.)

전역 공간을 더럽히지 않는 방법 🌻

  1. 전역 변수 X
  2. 지역 변수 O
  3. window, global을 조작 X
  4. const, let OK
  5. IIFE, Module, Closure , Scope 분리

임시 변수 제거하기

  • 임시 변수 혹은 객체를 어떻게 제거해야 메모리 공간을 차지하지 않는다.
const $ = (value) => {
    document.querySelector(value);
}

// 안 좋은 예
 function getElements1() {
     임시 객체 CRUD
     const result = {
        title : $('.title'),
        text : $('.text'),
        value : $('.value'),
    };
    return result;
 }
// 좋은 예
 function getElements2() {
    return {
        title : $('.title'),
        text : $('.text'),
        value : $('.value'),
    };
 }
  • 추가적인 스펙을 요구할 때 (날짜에 대한 요구 사항)
  • 내가 할 수 있는 것은 2가지 방식이 있다.
  1. 함수 추가
  2. 함수 수정 (문제가 생길 수 있다.)
  • 함수 수정 예시
// 잘못된 예
function getDateTime(targetDate) {
  let month = targetDate.getMonth();
  let day = targetDate.getDay();
  let hour = targetDate.getHour();

  month = month >= 10 ? month : "0" + month;
  day = day >= 10 ? month : "0" + day;
  hour = hour >= 10 ? hour : "0" + hour;

  return {
    month,
    day,
    hour,
  };
}
  • 함수 추가 예시
    • 임시 변수의 유혹을 벗어나야 한다. (추상화 과정을 거친다.)
    • 함수는 하나의 역할만 하도록 한다.
// 좋은 예
function getDateTime(targetDate) {
    const month = targetDate.getMonth();
    const day = targetDate.getDay();
    const hour = targetDate.getHour();

    return {
    month : month >= 10? month : '0' + month;
    day  : day >= 10? month : '0' + day;
    hour : hour >= 10? hour : '0' + hour;
    }

function getDateTime1() {
    const currentDateTime = getDateTime(new Date());
    return {
    month : computedKrDate(currentDateTime.month) +'분 전'
    day  : computedKrDate(currentDateTime.day) +'분 전'
    hour : computedKrDate(currentDateTime.hour) +'분 전'
    }
}
function genRandomNumber(min, max) {
  const randomNumber = Math.floor(Math.random() * (max + 1) + min);
  return randomNumber;
}

임시 변수를 제거해야 하는 이유?

  • 명령형으로 가득한 Logic이 나온다.
  • 어디서 어떻게 잘못되었는지 디버깅이 어렵다.
  • 추가적인 코드를 작성하고 싶은 유혹에 빠진다. (함수는 하나의 기능)

Solution 🌼

  • 함수 나누기
  • 고차 함수(map,filter,reduce)
  • 바로 반환
  • 선언형 프로그래밍