AND 연산자는 [두 가지]로 쓰인다.

ain·2022년 4월 2일
0

JavaScript

목록 보기
3/4
post-thumbnail
if(제가 잘못 이해하고 있는 부분이 있다면){
prompt("Please tell me what's wrong.");
} else {
document.write("thanks for visiting.");
}



1. && 는 두 가지로 쓰인다.


1.1 AND(&&)-1

두 피연산자가 모두 참일 때만 true를 반환하는 AND 연산자.

console.log(true && true); //true
console.log(true && false); //false
console.log(false && true); //false
console.log(false && false); //false

이렇게 피연산자 두개 모두 true일 때는 true를 반환하지만
false가 하나라도 들어가거나, 두개 모두 false일 경우에는 false가 반환된다.

우리가 JavaScript를 처음 배울 때 많이 보는 &&은 이 경우이다.





1.2 AND(&&)-2

피연산자를 하나씩 판단하면서 값을 변환하는 AND 연산자.

[rules]

  • 첫번째 피연산자부터 차례대로 판단하여 true면 다음 피연산자로 계속 판단을 이어가고, true아니면 그 값에서 멈추어 결과로 반환된다.(null이 나오면 null에서 멈추어 반환된다.)

  • 각 피연산자는 불린(boolean)으로 변환되어 판단한다.

  • 모든 피연산자가 true라면, 마지막 피연산자가 반환된다.

예시1)

console.log(true && true && true); //마지막 true값
console.log(true && false && true); //false
console.log(true && null && true); //null
console.log(true && undefined && true && null); //undefined

4번째 코드의 경우 마지막에 null이 있어도 차례대로 평가되는 것이기 때문에,
undefined에서 멈춰 undefined가 반환 된다.



예시2)

`value1`, `value2`, `value3`가 있다고 치자. 3개의 피연산자가 모두 true이면 `value3`가 출력되는 것이다. ```javascript console.log(value1 && value2 && value3); //value3 ```



예시3)★

이걸 이용해서 함수를 실행 시킬 수도 있다.
function이 존재할 때는 실행시키고,
function이 존재하지 않을 때에는 실행시키지 않을 때
AND 연산자를 쓸 수 있다.

function && function(argument)
//&&앞에 있는 function이 존재하면 true가 되어 
//&&뒤에 있는 function이 argument를 전달받아 실행시킴.
//반대로 false면 실행시키지 않음.

이 코드는 아래 코드와 같은 결과를 갖는다.

if (function) {
	function(argument);
}

특히 예시3)★은 조건문 대신 쓸 수 있는 코드이며, 코드를 간결하게 쓰기 위해 기억해 두면 좋을 것 같다!



2. [Today I Learned]

classcallback 함수에 관한 강의를 보던 중 이런 식의 코드가 나왔다.

class Counter {
//2번
  constructor(runEveryFiveTimes) {
    this.counter = 0;
    this.callback = runEveryFiveTimes;
  }
  increase() {
    this.counter++;
    console.log(this.counter);
    if (this.counter % 5 === 0) {
      this.callback(this.counter);
    }
  }
}
function printSomething(num) {
  console.log(`5의 배수 (${num})`);
}
function alertNum(num) {
  alert(`5의 배수 (${num})`);
}
//1번
const printCounter = new Counter(printSomething); 
const alertCounter = new Counter(alertNum);
printCounter.increase();
printCounter.increase();
printCounter.increase();
printCounter.increase();
printCounter.increase();
이 코드를 간단히 해석해 보자면,
숫자가 1부터 업데이트 되면서 5의 배수의 숫자의 차례가 되면 콘솔에 "5의 배수 (숫자)" 가 출력 되는 기능을 가지고 있는 printSomething 함수가 실행되는 코드이다.
출력되는 결과는 이렇다:

2.1 이 코드에서 if문의 역할은:

만약 출력되는 숫자가 5의 배수라면, printSomething(num)을 실행시켜라!
이다.

그리고 (주석처리 //1번)const printCounter = new Counter(printSomething)에서 만약 printSomething이 전달되지 않아 이 자리가 비었다면!!!->new Counter()

더이상 class 안에 있는 (주석처리 //2번)constructor에는
전달 될 argument가 없기 때문에 Error가 발생할 것이다.




2.2 Error를 고치기 위해 우리는:

(쉽게말하면) printSomething 함수가 new Counter()에 전달된다면
printSomething을 실행 할 것이고,
전달 되지 않는다면 실행 하지 않을 것이다.

즉,
전달된다면 5의 배수(5)가 콘솔에 출력 될 것이고,
전달 되지 않는다면 5의 배수(5)는 출력되지 않고 5까지만 출력될 것이다.

우리가 사용할 것은 [&&연산자]이다.



2.3 수정할 코드는 한줄밖에 되지 않는다:

class Counter {
  constructor(runEveryFiveTimes) {
    this.counter = 0;
    this.callback = runEveryFiveTimes;
  }
  increase() {
    this.counter++;
    console.log(this.counter);
    if (this.counter % 5 === 0) {
    //요기
      this.callback && this.callback(this.counter);
      /*if (this.callback) {
        this.callback(this.counter);
      }*/
    }
  }
}
function printSomething(num) {
  console.log(`5의 배수 (${num})`);
}
function alertNum(num) {
  alert(`5의 배수 (${num})`);
}
const printCounter = new Counter(printSomething);
const alertCounter = new Counter(alertNum);
printCounter.increase();
printCounter.increase();
printCounter.increase();
printCounter.increase();
printCounter.increase();

주석처리로 //요기 라고 되어있는 곳을 보면 이렇게 수정되어있다:

		this.callback && this.callback(this.counter);


정리해보면...
1. printSomething함수는 new Counter()에 전달 되었기 때문에 constructor(runEveryFiveTimes)자리에 들어갔다.
2. runEveryFiveTimes인자는 this.callback에 저장되어있다.
3. 결국 this.callbackprintSomething함수를 가르키고 있다.
파란글씨가 전부 printSomething 함수가 들어가는 자리라고 보면 된다.파랗게 불태웠다ㅎ



printSomething이 전달되었을 때:

  1. 현재 printSomething이 전달 되었으므로 &&앞에 있는 this.callbacktrue가 된다.
  2. &&뒤에 this.callback함수와 인자(this.counter)를 입력함으로써 이 마저도 true가 되어 함수가 실행되는 것이다!!!
  3. 결과:

printSomething이 전달되지 않았을 때:

  1. new Counter()에 printSomething이 전달 되지 않았을 때
//전달 되지 않은 코드
const printCounter = new Counter();
  1. 이렇게 되면 this.callback은 false가 되면서 &&뒤에 있는 this.callback(this.counter)도 실행이 되지 않는다.
  2. 결과:


마무리

  • 정리할 내용이 너무 많고 강조할게 많다보니 간결하게 쓰는게 어려운 것 같다.
    어떻게 하면 간결해 보이는지 많이 탐색해 봐야겠다.
  • 벨로그 처음이라 넘 열심히 썼더니 잔디 심는걸 깜빡했다





참조

profile
프론트엔드 개발 연습장 ✏️ 📗

0개의 댓글