부수 효과 : 산술 연산을 할 때 피연산자의 값을 변경
5+2; //7 부수효과x
5-2; //3 부수효과x
5*2; //10 부수효과x
5/2; //2.5 부수효과x
5%2; //1 부수효과x
var x = 1, sum;
//선할당 후 증가
sum = x++;
console.log(sum,x); //1,2
//선증가 후 할당
sum = ++x;
console.log(sum,x); //3,3
//선할당 후 감소
sum = x--;
console.log(sum,x); //3,2
//선감소 후 할당
sum = --x;
console.log(sum,x); //1,1
var x = '1';
console.log(+x);//1
console.log(x);//'1'
x = true;
console.log(+x);//1
console.log(x);//true
x = false;
console.log(+x);//0
console.log(x);//false
x = 'hi';
console.log(+x);//NaN
console.log(x);//'hi'
-(-10);//10
-'10';//-10
-true;//-1
-'hi';//NaN
+연산자는 피연산자 중 하나 이상이 문자열인 경우 문자열 연결 연산자로 동작
'1'+2; //'12'
1+2; //3
1+true; //2
1+false; //1
1+null;//1
+undefined;//NaN
1+undefined;//NaN
개발자의 의도와는 상관 없이 자바스크립트 엔진에 의해 암묵적으로 타입이 강제 변환(9장 타입 변환과 단축 평가) 된다.
var x;
x = 10; //x = 10
x+=5;//x = x + 5
console.log(x);//15
x-=5;//x = x - 5
console.log(x);//10
x*=5;// x = x * 5
console.log(x);//50
x/=5;// x = x / 5
console.log(x);//10
x%=5;// x = x % 5
console.log(x);//0
var x;
console.log(x = 10);//10
var a,b,c;
a = b = c = 0;
console.log(a,b,c);//0,0,0
동등 비교 연산자는 좌항과 우항의 피연산자를 비교할 때 암묵적 타입 변환을 통해 타입을 일치시킨 수 같은 값인지 비교하기 때문에 아래의 결과가 나온다.
5 == 5; //true
5 == '5'; //true
5 != 5; //false
5 != '5'; //false
일치 비교 연산자를 사용하면 타입도 같고 값도 같은 경우에 한하여 true를 반환한다.(암묵적 타입 변환을 하지 않는다.)
5 === 5;//true
5 === '5';//false
NaN === NaN; //NaN은 자신과 일치하지 않는 유일한 값
따라서 NaN을 조사하려면 빌트인 함수 isNaN을 사용해야 한다.
isNaN(NaN); //true
isNaN(1); //false
isNaN(1+undefined); //true
숫자 0도 주의해야하는데 0과 -0을 같은 취급한다.
0 === -0;//true
0 == -0;//true
Object.is 메서드를 사용하면 NaN과 0 문제를 전부 해결할 수 있다.
-0 === +0;//true
Object.is(-0,+0); //false
NaN === NaN;//false
Object.is(NaN,NaN);//true
5>0;//true
5>5;//false
5>=5;//true
5<=5;//true
조건식? 조건식이 true일 때 반환할 값: 조건식이 false일 때 반환할 값;
var result = score >= 60? 'pass' : 'fail';
//논리합(||)
true || true; //true
true || false; //true
false || true; //true
false || false; //false
//논리곱(&&)
true && true; //true
true && false; //false
false && true; //false
false && false; //false
//논리 부정(!)
!true;//false
!false;//true
!0; //true
!'Hello'; //false
'Cat' && 'Dog';//'Dog'
자세히 알고 싶다면 9.4절 단축평가를 참고하자
논리 연산자로 구성된 복잡한 표현식은 가독성이 좋지 않기 때문에 드 모르간의 법칙을 이용하면 복잡한 표현식을 좀 더 가독정 좋은 표현식으로 변환할 수 있다.
!(x||y) === (!x&&!y)
!(x&&y) === (!x||!y)
var x,y,x;
x = 1, y = 2, z = 3;//3
10*2+3;//23
10*(2+3);//50
typeof '' //'string'
typeof 1 //'number'
typeof NaN //'number'
typeof true //'boolean'
typeof undefined //'undefined'
typeof Symbol() //'symbol'
typeof null //'object'
typeof [] //'object'
typeof {} //'object'
typeof new Date() //object'
typeof /test/gi //'object'
typeof function(){} //'function'
여기서 주의해야할 점은
// undeclared라는 식별자를 선언한 적 없을 때
typeof undeclared; //undefined
2**2; //4
2**2.5; //5.65685424949238
-5**2;//SyntaxError 음수를 밑으로 사용하고 싶으면 괄호로 묶어줘야함
(-5)**2;//25
//지수연산자가 도입되기 이전엔 Math.pow()를 사용했다.
Math.pow(2,2); //4