연산자(operator) 정리

성민개발로그·2020년 11월 15일
0

자바스크립트

목록 보기
2/11

String

1.console.log('my'+'cat'); // 'mycat'
2.console.log('1'+2); // '12'
3.console.log(`string literals: 1 + 2 = ${1+2}`); 
// string literals: 1 + 2 = 3
  1. string 과 string 끼리 합쳐져서 결과가 나온다 결과: mycat
  2. number 타입과 string 타입이 더하면 string 이 우선순위다
  3. 백틱 으로 감싸고 ${} 여기 안에다가 연산이나 parameter를 가져와서 쓸수가있다 결과

increment and decrement operators

let counter =2 ;
const preIncrement = ++counter;
console.log(` postIncrement:${ preIncrement},counter:${counter}`)
//preIncrement:3,counter:3

++counter counter 에게 먼저 연산이 수행되고, 그 값을 preIncrement 에게 할당 해 준다.

let counter =2 ;
const postIncrement = counter++;
console.log(` postIncrement:${ postIncrement},counter:${counter}`)
//  postIncrement:2,counter:3

postIncrement 에게 counter 값을 먼저 할당을 해 주고 그 뒤에 counter 에게 +1 이 연산이 된다.
마이너스 도 동일하게 작동이 된다

Assignment operators

let x=3;
let y=6;
x +=y // x=x+y

Logical operators: ||(or),&&(and),!(not)

|| (OR):
첫번째가 참이면 바로 참을 반환하고 뒤에는 실행안함.
무거운 비교일수록 뒤에 배치해서 비교하는게 가장 이상적이다

const value1 = true;
const value2=4 < 2;
function check(){ // 의미없는 무거운함수 결론은 true를 반환하는 함수.
    for(let i=0;i<10;i++){
        //시간낭비
        console.log('wasting time')
    }
    return true;
}

console.log(`or:${value1 || value2 ||check()}`); //true 

함수를 맨뒤에 넣음으로써 첫번째value1 이 트루이기때문에 굳이 check()함수를 실행안하고 true 값이 반환이 된다.

&&(AND):
AND 연산자는 반대로 먼저 거짓이 나오면 뒤에 확인도 안하고 바로 false를 반환한다.

Equality ==,===

== 이 연산자는 string타입이든,number 타입이든 상관없이 같기만하면 참 을 반환한다

let stringFive ='5';
let numberFive = 5;
console.log(stringFive == numberFive); //true

=== 이것은 타입까지 확인하면서 비교를 진행한다 그래서 왠만하면 === 이것쓰는걸 추천

console.log(stringFive === numberFive);//false

object 비교 reference

const ellie1 ={name:'ellie'};
const ellie2 = {name:'sllie'};
const ellie3 = ellie1;
console.log(ellie1==ellie2);
//각각 다른 ref 가지고 있기때문에 false출력
console.log(ellie1===ellie2);
//각각 타입이 같든 안같든지 애초에 ref 가 다르기 때문에 false출력
console.log(ellie1===ellie3);
//ellie1을 ellie3한테 아예 덮어서 복사시킨 것이기 때문에 ref도 같고 타입도 똑같아서 true출력

break,continue

  • break:
    loop문 종료 시킬 때 사용.
  • continue:
    당장 실행중인 block만 나가게된다.

0개의 댓글