
논리 연산자는 조건문안에서 주로 사용되며 true인지 false인지 평가해야 하므로
논리연산자의 피연산자들은 Boolean형으로 형변환 된다.
const khw= {name: "khw"};
const kar ={name:"kar",age:19};
if(khw&&kar){ // true && true
console.log("true!"); // true
}
논리 연산자는 조건문 밖에서도 사용할 수 있는데 이때 논리 연산의 결과를 결정하는 피연산자를 형 변환하지 않고 그대로 반환하는 것
(조건이 truthy 일때 )&& (코드 실행)
const khw= {name: "khw"};
const kar ={name:"kar",age:19};
let result =khw&&kar;
console.log(result);
// khw는 boolean형으로 반환시 true(truthy)이므로 result로 kar이 들어간다.
function changeAge(obj){
obj.age= "바뀐 나이";
}
function makeAge(obj){
obj.age= "새로운 나이";
}
khw.age && changeAge(khw);
// khw.age가 false이므로 undefined return
kar.age && changeAge(kar);
// kar.age가 true이므로 changeAge(kar) 실행
console.log(khw); // { name: 'khw' } , 바뀌지 않음
console.log(kar); // { name: 'kar', age: '바뀐 나이' }
(조건이 falsy 일때 )|| (코드 실행)
const khw= {name: "khw"};
const kar ={name:"kar",age:19};
let result =khw||kar;
console.log(result);
// khw가 true이므로 뒤의 피연산자가 실행되지 않고 khw가 들어간다.
function changeAge(obj){
obj.age= "바뀐 나이";
}
function makeAge(obj){
obj.age= "새로운 나이";
}
khw.age || changeAge(khw);
// khw.age가 false이므로 changeAge(khw) 실행
kar.age || changeAge(kar);
// kar.age가 true이므로 kar.age return
console.log(khw); // { name: 'khw', age: '새로운 나이'}
console.log(kar); // { name: 'kar', age: '바뀐 나이' }
함수에서 기본 값을 설정하는 방법에는 2가지가 있다.
function helloWorld(value=1){
console.log(value);
}
helloWorld(undefined); // 1
helloWorld(); // 1
helloWorld(0); // 0
helloWorld(null); // null
function helloWorld(value){
console.log(value || 1);
}
helloWorld(undefined); // 1
helloWorld(); // 1
helloWorld(0); // 1
helloWorld(null); // 1
논리연산자 &&를 간결하게 표현하기위해 사용되는 연산자로 ?.로 표현한다.
// 중첩 객체
let apple ={name:'apple',style:{size:"small",color:"red"}};
// && 연산자 사용
function showSize(obj){ // size프로퍼티 값을 찾아주는 함수
return obj&&obj.style&&obj.style.size;
}
console.log(showSize()); // undefined
console.log(showSize(apple)); // small
// 중첩 객체
let apple ={name:'apple',style:{size:"small",color:"red"}};
// && 연산자 사용
function showSize(obj){
return obj?.style?.size;
}
console.log(showSize()); // undefined
console.log(showSize(apple)); // small
obj?.style?.size 실행 순서
(조건이 undefined 또는 null 일때 )|| (코드 실행)
let number; //undefined
console.log(number??1); // 1
number = null;
console.log(number ??1); // 1
number = 0;
console.log(number ?? 1); // 0