본문 바로가기
FE/javascript

JavaScript 단축 평가 논리 계산법, 비구조화 할당

by 빠니몽 2021. 2. 5.

21.02.04(+21.02.05)

 

 

1. 단축 평가 (short-circuit evaluation) 논리 계산법

논리 연산자를 조금 더 유용하게 사용하는 방법이다.

논리 연산자를 사용할 때, 우리는 꼭 boolean값만 사용 할 수 있는 것은 아니다.

 

예시.

const student = {
    name : "빠니몽"
};

function returnName(person) {
    if(person)
        return person.name;
    else
    	return undefined;
}

console.log(returnName(student));

위의 문장을 더 간단하게 줄일 수 있다.

const student = {
    name : "빠니몽"
};

function returnName(person) {
    return person && person.name;
}

console.log(returnName(student));	//빠니몽 출력

&&연산에서 'A && B' 일 때 A가 Truthy한 값이면 결과값은 B가 된다. 

만약 A가 Falsy한 값이면 결과값은 A가 된다.

A와 B가 모두 Falsy한 값이면 결과값은 B가 된다.


2. 비구조화(구조분해) 할당

2-1. 기본

const object = {
    a : 1,
    b : 2
};

const {a, b} = object;

console.log(a);		// 1출력
console.log(b);		// 2출력
const object = {
    a : 1,
    b : 2
};

function func({a, b}) {
	return {a, b};
}

const obj = func(object);

console.log(obj.a);		// 1출력
console.log(obj.b);		// 2출력

 

2-2. 비구조화에 디폴트값 주기.

const object = {
    a : 1,
};

function func({a, b = 3}) {
    return {a, b};
}

const obj = func(object);

console.log(obj.a);		// 1출력
console.log(obj.b);		// 3출력

 

2-3. 배열 비구조화로 받기

const array = [1,2];

const [a, b] = array;

console.log(a);		// 1출력
console.log(b);		// 2출력

 

2-4. 깊은 값 비구조화

const deepObject = {
  state: {
    information: {
      name: 'velopert',
      languages: ['korean', 'english', 'chinese']
    }
  },
  value: 5
};

const { name, languages } = deepObject.state.information;
const { value } = deepObject;

const extracted = {
  name,
  languages,
  value
};

console.log(extracted); // {name: "velopert", languages: Array[3], value: 5}

 

한 번에 뽑기

const deepObject = {
  state: {
    information: {
      name: 'velopert',
      languages: ['korean', 'english', 'chinese']
    }
  },
  value: 5
};

const {
  state: {
    information: { name, languages }
  },
  value
} = deepObject;

const extracted = {
  name,
  languages,
  value
};

console.log(extracted);

방식은 원하는 방향으로. 한 번에 뽑는 것보단 여러번에 걸쳐 뽑는게 깔끔할 수도 있음.