본문 바로가기
💻CODING/javascript

[js] 자바스크립트 코드 줄이는 방법

by 코딩하는 갓디노 2022. 1. 24.

[js] 자바스크립트 코드 줄이는 방법

 

js 코드를 더 짧게 줄이는 
몇가지 방법입니다. 

 

자바스크립트 코드 축약 방법

1. or 조건문 (||) 
2. and 조건문 (&&)
3. null, undefined, ' '  체크
4. 삼항연산자
5. 숫자 형변환

 

 

1. or 조건문 (||) 

|| 대신 includes()를 사용하면 끝없이 긴 조건문을 짧게 줄일 수 있습니다. 

 

before

if (a === 'hi' || a === 'hello' || a === 'hallo') {
  code...
}

 

after 

if (['hi', 'hello', 'hallo'].includes(a)) {
  code...
}

 

2. and 조건문 (&&)

  • ?. 연산자인 optional chaining operator를 사용하여 객체의 속성값을 접근합니다.
  • 속성 값이 없을 경우 undefinded를 반환합니다.
  • ?. 연산자로 코드도 줄일 수 있지만, 발생하는 type error 이슈를 해결할 수 있습니다. 

 

?. 연산자에 대한 자세한 예시는 아래 포스팅으로 이동해주세요.

https://goddino.tistory.com/257

 

[js] TypeError: Cannot read property 'x' of undefined (ft. javascript, react)

TypeError: Cannot read property 'x' of undefined 오류 해결입니다. 자바스크립트 또는 리액트에서 정말 자주 보게되는 오류 입니다. 어느 사이트에 의하면, Cannot read property 'x' of undefined, Can..

goddino.tistory.com

 

before

if (county && county.city && county.city.hospital) {
  code ...
}

 

after

if (county?.city?.hospital) {
  code ...
}

 

3. null, undefined, ' '  체크

  • or (||) 연사자를 이용하여 const a = data || 'nope'의 경우 data가 빈 값일 경우 nope 변수에 할당하게 됩니다.
  • 여기서 null, undefinded만 고려하고 싶을 때는 ?? 연산자를 사용합니다.
  • ?? 의 경우는 undefined, null의 경우에만 오른쪽 문장이 실행
  • ||의 경우는 false인 모든 경우에만 오른쪽 문장이 실행되므로 서로 다른 결과값을 나타낼 수 있습니다.

or 연산자, ?? 연산자에 대한 자세한 내용은 아래로 이동해주세요.

https://goddino.tistory.com/221

 

null 병합 연산자 '??' (ft. 기본값 매개변수, or 연산자 '||')

es6 최신 문법, null 병합 연산자에 대해 알아봅니다. null 병합 연산자 '??' (nullish coalescing operator) es6에서 새로 나온 문법 null 병합 연산자를 이용하여 매우 짧은 문법으로 코드를 심플하게 작성할.

goddino.tistory.com

 

before

let a
if (data !== null || data !== undefinded || data !== '') {
  a = data
} else {
  a = 'nope'
}

 

after - || 연산자

const a = data || 'nope' //data가 false인 경우에 'nope' 실행

 

after - ?? 연산자

const a = data ?? 'nope' //data가 undefinded, null인 경우에 'nope' 실행

 

여기서 data가 ' '인 경우에는 data가 할당됩니다.

const data = ''
const a = data ?? 'nope' //결과 ''

 

4. 삼항연산자

before

if (data == 'a') {
  코드1
} else {
  코드2
}

 

after

data === 'a' ? 코드1 : 코드2

 

5. 숫자 형변환

  • 보통 string type의 숫자를 number로 변환할때 parseInt, parseFloat를 자주 쓰지만, string type의 숫자 앞에 +만 붙여주면 number type으로 형변환이 됩니다. 

before

const target = '100'
console.log(parseInt(target))

 

after

const target = '100'
console.log(+target) //결과 100

 

반응형

댓글