javascript truthy falsy

agnusdei·2023년 10월 30일

JavaScript에서 "truthy"와 "falsy"는 조건식에서 값이 논리적으로 평가될 때 값의 진리성(참 또는 거짓)을 나타냅니다. JavaScript에서는 다음과 같은 값들이 "falsy" 또는 "truthy"로 평가됩니다.

Falsy 값 (False와 유사한 값):
1. false: 불리언 false 값
2. 0: 숫자 0
3. -0: 음수 0
4. 0n: BigInt 0
5. '' 또는 "": 빈 문자열
6. null: null 값
7. undefined: undefined 값
8. NaN: 숫자가 아님 (Not-a-Number)

Truthy 값 (True와 유사한 값):
1. true: 불리언 true 값
2. 어떤 숫자(0 이외의 숫자)
3. 어떤 문자열(빈 문자열이 아닌 문자열)
4. 어떤 객체(배열, 함수, 객체 등)
5. []: 빈 배열
6. {}: 빈 객체
7. 함수: 정의된 함수
8. 모든 객체(사용자 정의 객체 또는 내장 객체)

다양한 코드 예시를 통해 "truthy"와 "falsy"를 이해해보겠습니다:

if (true) {
  console.log('This is truthy');
}

if (false) {
  console.log('This is falsy'); // 이 부분은 실행되지 않음
}

if (0) {
  console.log('This is falsy'); // 이 부분은 실행되지 않음
}

if (1) {
  console.log('This is truthy');
}

if ('Hello, World!') {
  console.log('This is truthy');
}

if ('') {
  console.log('This is falsy'); // 이 부분은 실행되지 않음
}

if ([]) {
  console.log('This is truthy');
}

if ([]) {
  console.log('This is truthy'); // 빈 배열도 truthy
}

if ({}) {
  console.log('This is truthy');
}

if (null) {
  console.log('This is falsy'); // 이 부분은 실행되지 않음
}

if (undefined) {
  console.log('This is falsy'); // 이 부분은 실행되지 않음
}

if (NaN) {
  console.log('This is falsy'); // 이 부분은 실행되지 않음
}

if (function() {}) {
  console.log('This is truthy');
}

if (0n) {
  console.log('This is falsy'); // 이 부분은 실행되지 않음
}

이렇게 "truthy"와 "falsy"는 조건문과 논리 연산에서 중요하게 사용되며, 값의 진리성을 판단할 때 유용합니다.

profile
DevSecOps, Pentest, Cloud(OpenStack), Develop, Data Engineering, AI-Agent

0개의 댓글