상세 컨텐츠

본문 제목

[JavaScript] JavaScript #3: 연산자, 타입변환, 단축 평가

PROGRAMMING/Web

by koharin 2021. 1. 30. 00:13

본문

728x90
반응형

자바스크립트에서 다른 프로그래밍 언어와 다른 부분들만 정리해봤다.


+true // 1

+false // 0



1 + true // 2

1 + false // 1

1 + null // 1 (null -> 0)

1 + undefined // NaN (undefined -> NaN)
var str = 'My name is ';
str += 'Lee'; // My name is Lee

var x;
console.log(x = 10); // 10

var x,y;
y = x = 10;
// var x = y = 10;
console.log(x,y) // 10 10

5 == '5' // true (암묵적인 타입 변환으로 같은 값을 가짐)

 

비교/일치 연산자


비교 연산자 의미
== x와 y의 값이 같음
=== x와 y의 값과 타입이 같음
!= x와 y의 값이 다름
!== x와 y의 값과 타입이 다름
NaN === NaN // false

isNaN(NaN) // true
  • NaN은 자신과 일치하지 않는 유일한 값으로, isNaN으로 숫자가 NaN인지 판별해야 한다.

 

삼항 연산자


var x = 2;

var result = x % 2 ? 'odd' : 'even';

console.log(result); // even
  • x % 2 결과가 0일 때, 0은 false이므로 false일 때를 even으로 한다.
var foo = null;

console.log(typeof foo === null); // false
console.lof(foo === null); //true
  • null 타입인지 확인할 때는 일치 연산자(===)를 사용해야 한다.

 

var num = 2;

var kind = num ? (num > 0 ? 'positive' : 'negative') : 'zero';
console.log(kind) // positive
  • 0은 false이므로 num이 0일 경우 false로 'zero'가 출력될 것이고, 0이 아닐 경우에는 괄호 안의 표현식에 들어간다.

 

타입 변환


1. 명시적 타입변환(Explicit coercion)/타입 캐스팅(Type Casting)

var x = 10;
var str = x.toString(); // Explicit coercion || type casting
console.log(typeof str); // string
  • 개발자의 의도적인 타입 변환

2. 암묵적 타입 변환(Implicit coercion)/타입 강제 변환(Type coercion)

var x = 10;

var str = x + ''; // Implicit coercion
console.log(typeof str, str); // string 10
console.log(x); // 10
  • 자바스크립트 엔진에 의한  문맥(context)를 고려하여 암묵적인 타입 자동 변환을 수행하고, 표현식을 평가한다.

 

Falsy 값


false
undefined
null
0, -0
NaN
''
  • boolean으로 false로 평가된다. (Falsy 값)

 

명시적 타입 변환


//문자열
console.log(String(1)); // '1'
console.log((1).toString()); // '1'

// 숫자
console.log(Number('0')); // 0
console.log(parseInt('0')); // 0
console.log(parseFloat('5.16')); // 5.16
console.log(true * 1); // 1
console.log(false * 1); // 0

// Boolean
console.log(Boolean('x')); // true
console.log(Boolean('')); // false
console.log(Boolean('false')); // true
console.log(Boolean(NaN)); // false
console.log(Boolean(null)); // false
console.log(Boolean(undefined)); // false
console.log(Boolean(0)); // false
console.log(Boolean(Infinity)); // true
console.log(!!'x'); // true
console.log(!!''); // false
console.log(!!{}); // true
console.log(!![]); // true

 

 

단축 평가


단축 평가 표현식 평가 결과
true && anything anything
false && anything false
true || anything true
false || anything anything
'Cat' && 'Dog' // "Dog"
  • 'Cat'과 'Dog' 모두 true로 평가되는데, 논리곱 연산 결과는 두번째 피연산자인 'Dog'이다.
  • 논리곱 연산자(&&)는 논리 연산의 결과를 결정한 두 번째 피연산자의 평가 결과를 반환한다.

 

'Cat' || 'Dog' // "Cat"
  • 논리합 연산자(||)는 논리 연산의 결과를 결정한 첫 번째 피연산자의 평가 결과를 반환한다.

 

728x90
반응형

관련글 더보기