늘 겸손하게

JavaScript - 논리연산자 '&&', '||' 본문

Programming/JavaScript

JavaScript - 논리연산자 '&&', '||'

besforyou999 2023. 8. 26. 16:47

 

AND 연산자 ' &&'

 

 

기호 '&&'

 

피연산자들이 모두 Truthy 값인 경우 true를 반환하는 연산자.

 

const a = true;
const b = true;
const c = false;

if (a && b) {
  console.log("a && b");    // "a && b"
}

if (a && b && c) {
  console.log("a && b && c");    // 실행 안됨
}

console.log(1 && 2);    // 2

 

유의할 점은 가장 왼편에 있는 피연산자에서 가장 오른편에 있는 피연산자 순으로 탐색하여 가장 먼저 발견된 Falsy값을 반환한다는 점입니다.

 

Falsy값이 발견되지 않았다면 가장 오른편에 있는 피연산자를 반환합니다.

 

 

예시

const a = 1;
const b = 0;

// AND 연산자
console.log(a && b);        // 0
console.log(1 && 0);        // 0
console.log(1 && 2 && 0);   // 0
console.log(1 && 0 && 2);   // 0
console.log(0 && 1 && 2);   // 0
console.log('A' && 'B' && 'C'); // 'C'

 

 

 

OR 연산자 '| |'

 

 

기호 '| |'

 

피연산자들 중 하나라도 Truthy 값이 있으면 True를 반환하는 연산자.

 

const a = true;
const b = false;
const c = false;

if (a || b || c) {
  console.log("a or b or c"); // a or b or c
}

if (b || c) {
  console.log("b or c");  // 실행 안됨
}

 

유의할 점은 AND 연산자와 마찬가지로 가장 왼쪽에서 오른쪽 피연산자 순으로 탐색하여 가장 먼저 발견된 Truthy값을 반환한다는 점입니다.

 

Truthy값이 없을 경우 마지막 피연산자를 반환합니다.

 

 

예시

console.log(false || true);     // true
console.log(0 || 1);            // 1
console.log(false || 0 || {});  // {}
console.log(false || [] || null); // []
console.log(function() {} || undefined || null);  // [Function (anonymous)]

console.log(false || 0 || null);  // null