728x90
반응형
논리연산자를 이용해서 코드를 더 짧게 사용하는 것을 말한다.
전에 있던 Truthy한 값과 Falsy한 값에서 좀 더 나아가보자.
const dog = {
name: '멍멍이'
}
function getName(animal) {
// 1번째 코드
if(animal) {
return animal.name;
}
return undefined;
//-----------------------------------
// 2번째 코드
return animal && animal.name
}
const name = getName(dog);
console.log(name)
위의 코드에 1번과 2번은 같은 결과를 내준다.
2번 코드가 어떻게 1번과 같을까?
앞에 부분이 true가 되면 뒤의 값이 오게 된다.
아래의 코드를 보면 좀 더 쉽게 이해할 수 있다.
console.log(true && 'hello'); //true면 연산결과가 뒤에 오는것이 된다.
console.log(false && 'hello');
console.log('hello' && 'hello'); //앞에 있는 것이 true면 오른쪽에 있는 결과물이 온다.
console.log('' && 'hello');
console.log(0 && 'hello');
console.log(1 && 'hello');
console.log(1 && 1);
&& 연산자는 앞에 오는 것이 truthy한 값이면 결과는 오른쪽에 있는 값이 된다.
만약에 앞에 있는 값이 falsy한 값이면 앞에 있는 값이 온다.
//1.
const object = { name : 1};
//2.
const object = null;
//3.
const object = { name : '메롱'}
//4.
const name = object && object.name
object의 값이 만약에 null인 경우도 생긴다면 4번의 코드처럼 처리할 수 있다.
&&를 알아봤으니 || 를 알아본다.
const namelessDog = {
name : '',
}
function getName(animal) {
const name = animal && animal.name;
if(!name) {
return '이름이 없는 동물입니다.'
}
return name;
}
const name = getName(namelessDog);
console.log(name);
이런 코드를 어떻게 하면 && 같이 간결하게 쓸 수 있을까?
const namelessDog = {
name : '',
}
function getName(animal) {
const name = animal && animal.name;
return name || '이름이 없는 동물입니다.'
}
const name = getName(namelessDog);
console.log(name);
console.log(false || 'hello')
console.log('' || '이름없다')
console.log(null || 'null!!!')
console.log(undefined || 'defined 안됨.')
console.log(0 || '0이네?')
console.log(1 || '1이네??')
console.log(true || '여기안봄')
console.log('오?' || '여기 안봄.')
console.log([] || '노')
falsy한 값이면 뒤의 값이 온다.
truthy한 값이면 뒤의 값을 보지않는다.
즉, &&와는 반대의 성향이다.
|| 연산자는 어떤 값이 없을 때 그것 대신에 이것을 사용할것이다 할 때 쓰게된다.
반응형
'개발자의 공부방 > Frontend' 카테고리의 다른 글
javascript] 비구조화 할당 (0) | 2021.12.18 |
---|---|
javascript] 함수의 기본파라미터 (0) | 2021.12.16 |
javascript] Truthy와 Falsy (0) | 2021.12.15 |
javascript] property shorthand란? (0) | 2021.12.06 |
vue] vue.js 경로 '@' 의미 (0) | 2021.11.29 |