[javascript] Truthy값과 falsy값, 단축평가 응용하기

2022. 3. 18. 13:48프론트엔드/JavaScript

반응형

 

Truthy & falsy

 

Boolean 값인 true, false 를 가지지 않음에도 불구하고 그와 비슷한 효과를 내는 값들이다.

먼저 falsy 값을 알아보자면, 다음과 같다.

 

falsy 값의 종류

false 키워드 false
0 숫자 zero
-0 음수 zero
0n BigInt. 불리언으로 사용될 경우, 숫자와 같은 규칙을 따름. 0n은 거짓 같은 값.
""  string
null null - 아무런 값도 없음
undefined undefined - 원시값
NaN (en-US) NaN - 숫자가 아님

 

falsy 값이 자바스크립트에서 불리언 값을 요구하는 부분에 들어가면, 이 값들은 false로 변환된다.

즉 조건문이나 반복문에 들어가면 false로 작동하는 것이다.

falsy 값의 자동 형 변환

 

if (false)
if (null)
if (undefined)
if (0)
if (-0)
if (0n)
if (NaN)
if ("")
// 모두 bypass (실행되지 않음)

 

 

falsy에 해당하지 않은 모든 값은 truthy 값으로 보면 된다.

 

단, 이는 불리언 값을 요구하는 부분에서 자바스크립트 내부적으로 그 형 변환이 일어날 뿐이지,

절대 true, false 값과는 같지 않다.

if (undefined === false) // false

 

 

 

단축 평가 : 논리 연산자를 좀 더 유용하게 사용하는 법

 

논리연산자

논리곱 && : 두 개의 피연산자가 모두 true 일때 true를 반환

논리합 || : 두 개의 피연산자 중 하나만 true여도 true를 반환

 

true && true // true
true && false // false
true || false // true
false || true // true

 

단축평가

논리곱, 논리합 연산자는 논리 연산의 결과를 결정하는 피연산자를 타입 변환하지 않고 그대로 반환한다.

단축평가는 표현식을 평가하는 도중에 결과가 확정된 경우 나머지 과정을 생략한다.

true || anything // true
false || anything // anything
true && anything // anything
false && anything // false

 

논리연산자를 사용할 때 무조건 boolean 값을 사용해야하는 것은 아니다.

문자열, 숫자, 객체를 이용할 수 있고, 이 때 그 값이 truthy/ falsy 에 따라 결과가 달라진다.

 

false && "dog"
// ↪ false
0 && "dog"
// ↪ 0

//If the first object is falsy, it returns the first object
console.log(true && 'hello'); // hello
console.log(false && 'hello'); // false
console.log('hello' && 'bye'); // bye
console.log(null && 'hello'); // null
console.log(undefined && 'hello'); // undefined
console.log('' && 'hello'); // ''
console.log(0 && 'hello'); // 0
console.log(1 && 'hello'); // hello
console.log(1 && 1); // 1
console.log(true || 'hello'); // true
console.log(false || 'hello'); // hello
console.log('hello' || 'bye'); // hello
console.log(null || 'hello'); // hello
console.log(undefined || 'hello'); / /hello
console.log('' || 'hello'); // hello
console.log(0 || 'hello'); // hello
console.log(1 || 'hello'); // 1
console.log(1 || 1); // 1

 

A && B 일 때, A가 truthy면 B가 결과값이 되고, A가 falsy 면 A가 결과값이 된다.

A || B 일 때, A가 truthy면 A가 결과값이 되고, A가 falsy 면 B가 결과값이 된다.

 

A && B
// A가 truthy면, B가 결과값
// A가 falsy면, A가 결과값

A || B
// A가 truthy면, A가 결과값
// A가 falsy면, B가 결과값

 

 

단축평가 응용편

 

논리 연산자 표현식으로 if문 대체가 가능하다.

어떤 조건이 truthy값일 때 무언가를 해야한다면,

var done = true;
var message = '';

//주어진 조건이 true일 때
if (done) message = '완료';

//done이 true라면 message에 '완료'할당
message = done && '완료';
console.log(message); //완료

 

 

어떤 조건이 falsy값일 때 무언가를 해야한다면,

var done = false;
var message = '';

//주어진 조건이 false일 때
if (done) message = '미완료'

//done이 false라면 message에 '미완료'할당
message = done || '미완료';
console.log(message); //미완료
const userName = null; 
const msg = userName || "고객";
console.log(`어서오세요 ${msg}님`);
// userName의 값이 있으면 출력, 없으면(null) 고객님 출력

 

 

if...else 문 대체도 가능하다

var done = true;
var message = '';

//if...else문
if (done) message = '완료'
else	  message = '미완료'
console.log(message); //완료

message = done ? '완료' : '미완료';
console.log(message); //완료

 

변수가 객체인지 확인하고 프로퍼티를 참조할 때

var elem = null;
var value = elem.value; // TypeError: Cannot read property 'value' of null
var value = elem && elem.value; // null
// elem이 null이나 undefined와 같은 Falsy 값이면 elem으로 평가
// elem이 Truthy 값이면 elem.value로 평가

 

함수 매개변수에 기본값을 설정할 때

// 단축 평가를 사용한 매개변수의 기본값 설정
function getStringLength(str) {
  str = str || '';
  return str.length;
}

getStringLength(); // 0
getStringLength('hi'); // 2

// ES6의 매개변수의 기본값 설정
function getStringLength(str = '') {
  return str.length
}

getStringLength(); // 0
getStrringLength('hi'); // 2

 

 

truthy와 falsy값을 이용하면 잡기 어려운 에러도 쉽게 방지할 수 있다.

 

// instead of
if (x == false) // ...
// runs if x is false, 0, '', or []

// use
if (!x) // ...
// runs if x is false, 0, '', NaN, null or undefined

 

// instead of
if (x == y) // ...
// runs if x and y are both truthy or both falsy
// e.g. x = null and y = undefined

// use
if (x === y) // ...
// runs if x and y are identical...
// except when both are NaN

 

// instead of
if (x === y) // ...
// runs if x and y are identical...
// except when both are NaN

// use
if (Boolean(x) === Boolean(y)) // ...
// or
if (!!x === !!y) // ...
// runs if x and y are identical...
// including when either or both are NaN

 

Boolean 생성자는 truthy는 true값으로, falsy는 false로 반환하기 때문에

아래와 같은 응용도 가능하다.

const truthy_values = [
  false,
  0,
  ``,
  '',
  "",
  null,
  undefined,
  NaN,
  '0',
  'false',
  [],
  {},
  function() {}
].filter(Boolean);

// Filter out falsy values and log remaining truthy values
console.log(truthy_values); // 0, 'false', [], {}, function() {}

 

 

 

https://developer.mozilla.org/en-US/docs/Glossary/Falsy

https://learnjs.vlpt.us/useful/03-short-circuiting.html

https://velog.io/@najiexx/JavaScript-%EB%8B%A8%EC%B6%95-%ED%8F%89%EA%B0%80

https://www.sitepoint.com/javascript-truthy-falsy/

 

 

 

 

 

반응형