operator, if, for loop

김민재·2021년 7월 11일
0

Gotcha JavaScript!

목록 보기
13/45

operator

1. String concatenation

  • +기호를 이용해 문자열과 문자열을 합쳐서 새로운 문자열을 만든다.
  • 백택 기호를 활용하여 string literals를 만들 수 도 있다.
    -string literals를 사용하면 줄바꿈을 하거나 특수기호, 싱글쿼트를 이용해도 문자열로 변환이 된다.
    -일반적으로 싱글쿼트''를 특수 기호로 인식하기 위해서 \ 백슬러시를 넣어줘야한다. 줄바꿈을 새로 할때는 \n을 \t는 탭키이다.

2. Numeric operators

  • 숫자들을 더하고 빼고 나누고 곱하고 나머지 값 제곱 값 등의 연산이 가능하다

3. increment and decrement operators

-preIncrement는 변수 앞에 ++을 붙여 바로 1을 증가시켜준다.
-postIncrement 변수 뒤에 ++을 붙여 변수의 값을 postIncrement에 할당 한 뒤에 1의 증가는 그 뒤에 일어난다.
-preDecrement, postDecrement 역시 동작원리는 동일하다.

let counter = 2;
const preIncrement = ++counter;
// counter = counter + 1;
// preIncrement = counter;
console.log(`preIncrement: ${preIncrement}, counter: ${counter}`);
// counter에 1을 더한 그 값을 할당한 뒤 preIncrement 변수에 counter에 값을 할당한다.
const postIncrement = counter++;
// postIncrement = counter;
// counter = counter + 1;
console.log(`postIncrement: ${postIncrement}, counter: ${counter}`);

4. Assignment operators

-할당시 사용하는 연산자
-=, +=,-=,*=,/=처럼 축약해서 쓰기도함

5. Comparison operators

-비교시 사용하는 연산자
-<, <=,>,>=

6. logical operators

-|| (or), && (and), ! (not)
-||, or연산자는 첫 조건으로 처음에 true면 거기서 멈추게된다.
-심플한 value와 같은 것을 앞에 두고 복잡하고 무거운 익스프레이션이나 함수를 호출하는 조건을 가장 뒤에다가 배치하는 것이 좋다.
-&&, and연산자는 모두 true여야만 true를 리턴한다. and 역시 무거운 오퍼레이션일수록 가장 뒤에 배치하여&&, and연산자 체크하는 것이 좋다.
-&&, and연산자 간단하게 null을 체크할 때도 많이쓰인다. nullableObject가 null이 아닐 때만 nullableObject.something value를 받아올 수 있다.
-!, not연산자는 true와 false를 반대값으로 바꿔준다.

if(nullableObject != null) {
nullableObject.something;
}
// || (or), finds the first truthy value
console.log(`or: ${value1 || value2 || check()}`);
// && (and), finds the first falsy value
console.log(`and: ${value1 && value2 && check()}`);
// often used to compress long if-statement
// nullableObject && nullableObject.something

function check() {
  for (let i = 0; i < 10; i++) {
    //wasting time
    console.log('😱');
  }
  return true;
}

7. Equality

  • == loose equality, with type conversion, 즉 타입을 변경해서 검사를 한다.
  • === strict equality, no type conversion, 타입을 신경써서 타입이 다르면 다르다는 결과값을 준다.
console.log(stringFive == numberFive);
console.log(stringFive != numberFive);

console.log(stringFive === numberFive);
console.log(stringFive !== numberFive);
  • Equality 공부할 땐 object의 참조를 신경써서 공부해야한다.
// object equality by reference
const ellie1 = { name: 'ellie' };
const ellie2 = { name: 'ellie' };
const ellie3 = ellie1;
console.log(ellie1 == ellie2);//ellie1와 ellie2 각각 다른 레퍼런가 저장되어 false
console.log(ellie1 === ellie2);//ellie1와 ellie2도 서로 다른 레퍼런가 저장되어 false
console.log(ellie1 === ellie3);//ellie1와 ellie3도 같은 레퍼런에 저장되어 true

8. Conditional operators

  • if, else if, else

9. Ternary operator: ?

  • condition ? value1 : value2; 과 같은 형식으로 간단한 if문을 쉽게 쓸 수 있다.
  • 조건문에다가 ?를 붙이면 true인지 물어보고 true면 왼쪽을 false면 오른쪽을 실행한다.
console.log(name === 'ellie' ? 'yes' : 'no');

10. Switch statement

  • switch 조건문 안에 있는 값이 해당되는 case에 있는 부분을 실행한다.
  • if문에서 else if를 반복하는 경우에 쓰면 유용하다.
const browser = 'IE';
switch (browser) {
  case 'IE':
    console.log('go away!');
    break;
  case 'Chrome':
  case 'Firefox':
  //같은 결과를 실행하는 경우 케이스를 연달아 붙일 수 도 있다.
    console.log('love you!');
    break;
  default:
    console.log('same all!');
    break;
}

11. Loops

1> whlie문은 조건이 false가 나오기 전까지 반복해서 돈다.

  • while loop, while the condition is truthy, body code is executed.
    2> do while문은 먼저 블록을 실행한 뒤에 조건을 검사하며 반복을 돈다.
  • while loop, body code is executed first, then check the condition.
do {
  console.log(`do while: ${i}`);
  i--;
} while (i > 0);

3> for loop, for(begin; condition; step),시작 조건 어떤 스텝을 밟을건지 명시하여 반복문을 돈다.

  • 기존에 존재하는 변수를 할당할 수 도 있고 for안에서 지역변수를 선언해서 작성할 수 도 있다.
    4> nested loops, 중첩 반복문
profile
자기 신뢰의 힘을 믿고 실천하는 개발자가 되고자합니다.

0개의 댓글