본문 바로가기
Javascript

JavaScript 코드 꿀팁들

by ttum 2020. 4. 5.

얼마 전 유튜브에서 'JavaScript Pro Tips - Code This, NOT That' 영상을 보다가 새로 알게된 신기한 것들이 있어 정리하게 되었다.

1. console.log 출력하는 방법

console.log를 이용해 여러 가지 것들을 출력하다보면 어디서 출력한 것인지 체크하기 위해서,

const fruit1 = "apple";
const fruit2 = "apple";
const fruit3 = "apple";

console.log('fruit1', fruit1);
console.log('fruit2', fruit2);
console.log('fruit3', fruit3);

이런 식으로 이름을 명시해주고 적을 때가 종종 있다. 여간 번거로운 작업이 아니다.

이때 사용할 수 있는 간편한 방법이 있다.

console.log({ fruit1 });
console.log({ fruit2 });
console.log({ fruit3 });

이 방법은 이전에 작성한 ES6문법을 정리한 글에서도 언급했던 객체의 속성 이름과 value에 넣고자 하는 변수의 이름이 같을 때 축약해서 쓸 수 있는 Syntactic sugar이다. 위의 코드를 다시 길게 써보자면 아래 코드와 같은 것이다.

console.log({ fruit1: fruit1 });
console.log({ fruit2: fruit2 });
console.log({ fruit3: fruit3 });

 

결과는 아래처럼 깔끔하게 출력이 된다 :)

 

2. 크롬 콘솔창에 CSS효과 넣기

(절대 쓸 일은 없을 것 같지만 신기해서 적어보는 내용 ㅎㅎ. 크롬 개발자도구 콘솔창에서 적용되고 일반 GUI가 없는 터미널에서는 적용되지 않는다.)

console.log(`%chappy`, "color: orange; font-size: 2em;");

위와 같이 %c를 입력하고 뒤에 출력할 것을 입력한다. 그리고 함수의 두번째 인자로 css 속성을 넣어주면 된다.

이렇게 콘솔창에 CSS 속성이 적용된 채로 나온다.

 

3. 객체들을 표 형식으로 콘솔창에 출력하기

console.table() 함수를 이용해 객체들을 한 눈에 보기 좋게 출력할 수 있다.

const foo = { name: "foo", age: 30, happy: true };
const bar = { name: "bar", age: 40, happy: false };
const baz = { name: "baz", age: 50, happy: true };

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

4. 템플릿 리터럴 (Template literal)

ES6문법을 정리할 때 백틱에 대해서는 이미 언급했었다.

조금 더 심화된 내용인 Tagged template이 있는데, Tag를 이용해 템플릿 리터럴을 함수로 파싱할 수 있다.

function tags(strings, name, feeling) {
  return `${strings[0]}${name}${strings[1]}${feeling}${strings[2]} Let's play tennis!`;
}

const name = "sumin";
const feeling = "happy";
const str = tags`Hello my name is ${name}. I am ${feeling} to see you.`;
console.log({ str });

// result: { str: "Hello my name is sumin. I am happy to see you. Let's play tennis!" }

복잡해보이지만 strings의 의미만 알면 어렵지 않다. strings는 str을 ${} 기준으로 나눈 것이다.

따라서 strings는 [ 'Hello my name is ', '. I am ', ' to see you.' ] 와 같은 배열이다.

바로 문장을 return 해줘도 되지만 고계함수로서 함수를 리턴해줄 수도 있다.(다른 예시들)