2.11 Logical operator

히진로그·2022년 2월 2일
0

Modern-Javascript

목록 보기
8/14

출처: https://javascript.info/

  • 혼자 읽고 타이핑하며 이해하면서 공부한 흔적 남기기

There are four logical operators in JavaScript:

||(OR), &&(AND), !(NOT), ??(Nullish Coalescing).

Although they are called "logical", they can be applied to values of any type, not only boolean. Their result can also be of any type.

비록 '논리적'이라 불리지만 그들은 boolean 뿐 아니라 어느 타입의 vlaue에도 적용될 수 있다.

그들의 결과는 어느 타입이든 될 수 있다.

||(OR)

If operand is not a boolean, it's converted to a boolean for the evalutation.

인수가 boolean값이 아니면 값을 구하기 위해 boolean값으로 바꾼다.

Most of the time, OR || is used in an if statement to test if any of the given condition is true.

OR "||" finds the first truthy value

result = value1 || value2 || value3;

The OR || operator does the following:

  • Evaluates operands from left to right

왼쪽에서 오른쪽으로 인자를 평가한다.

  • For each operand, converts it to boolean. If the result is true, stops and returns the original value of that operand.

각 인자를 boolean으로 변환한다. 만약 그 결과가 true라면 변환을 멈추고 true인 원래 값을 리턴한다.

  • If all operands have been evaluated(i.e. all were false), return the last operand.

모든 인자가 변환되었다면(즉, 모두 false라면), 가장 마지막 인자를 리턴한다.

A value is returned in its original form, without the conversion.

값은 변환되지 않은 원래 형태로 리턴된다.

In other words, a chain of OR || returns the first truthy value or the last one if no trurthy value is found.

다시말해서, OR은 첫 번째 true값을 리턴하고, 모두 false라면 마지막 값을 리턴한다.

  1. Short-circuit evaluation

It means that || processes its arguments until the first truthy value is reached, and then the value is returned immediately, without even touching the other argument.

자신의 인수를 첫 번째 true가 나올때까지 평가하고, 찾는 즉시 다른 인수는 건드리지 않고 바로 결과를 리턴한다.

The importance of this feature becomes obvious if an operand isn't just a value, but an expression with a side effect, such as a variable assignment or a function call.

이 형식은 인자가 그냥 값이 아니라 함수호출이나 변수 할당과 같은 부작용이 있는 표현식인 경우 분명해진다.

true || alert('not printed');
false || alert('printer');

In the first line, the OR || operator stops the evaluation immediately upon seeing true, so the alert isn't run.

첫 번째 줄에서 오퍼레이터가 true를 보는 즉시 평가를 멈추기 때문에 alert는 실행되지 않는다.

Sometimes, people use this feature to execute commands only if the condition on the left part is falsey.

&&(AND)

The AND operator is represented with two ampersands &&.

In classical programming, AND returns true if both operands are truthy and false otherwise.

AND "&&" finds the first falsy value

The AND && opertar does the following

  • Evaluates operands from left to right.
  • For each operand, converts it to a boolean. If the result is false, stops and returns the original value of that operand.
  • If all operands have been evaluated(i.e. all were truthy), returns the last operand.

즉, AND는 첫 번째 falsy 값을 리턴하거나 마지막 true 값을 리턴한다.

Precedence of AND && is higher than OR ||

&& > ||

!(NOT)

!(exclamation sign)

result = !value;

The operator accepts a single argument and does the following

  • Converts the operand to boolean type: true/false.
  • Returns the inverse value.

A double NOT !! is sometimes used for converting a value to boolean type

이중 NOT !!은 값을 boolean type으로 바꾸기 위해 가끔 사용된다.

alert(!!"non-empty string"); // true
alert(!!null); // false

첫 번째 !는 값을 boolean으로 바꾸고 값을 inverse 해준다. 두번째 !는 그 값을 다시 inverse한다.

즉, 원래 값의 boolean type을 리턴한다.

The precedence of NOT ! is the highest of all logical operators, so it always executes first, before && or ||.

! > && , ||

Task

alert(alert(1) || 2 || alert(3)); // 1, 2

The call to alert does not return a value. Or, in other words, it returns undefined.

→ it just shows a message, so there's no meaningful return)

  1. The first OR evaluates its left operand alert(1). That shows the first message with 1.
  2. The alert returns undefined, so OR goes on to the second operand searching for a truthy value.
  3. The second operand 2 is truthy, so the execution is halted, 2 is returned and then shown by the outer alert.

There will be no 3, because the evaluation does not reach alert(3).

alert(null || 2&&3 || 4); // 3

&&가 우선순위니까 먼저 값을 내면 3임.

그리고 OR을 실행하면 첫 번째 true값인 3이 최종적으로 리턴됨.

let name = prompt("Who's there?");
let password;

if(name == "Admin") {
    password = prompt("Passwords?");
} else if (name == "" || null) {
    alert("Canceled");
} else {
    alert("I don't know you");
}

if(password == "The Master") {
    alert("Welcome!");
} else if(password == "" || null) {
    alert("Canceled");
} else {
    alert("wrong passwords");
}

내 코드에 확신을 가지자.

password를 if 문 안에서 정의하는 것 까지 생각했는데,, 색이 죽는 걸 보고 틀렸구나 생각하고 이상하게 코드를 짠 결과. 이상하게 동작..

let userName = prompt("Who's there?",'');

if(userName === 'Admin') {
    let pass = prompt('Passwords?', '');

    if(pass === 'The Master') {
        alert('Welcome!');
    } else if(pass === '' || pass === null) {
        alert('Canceled');
    } else {
        alert('Wrong password');
    }
} else if(userName === '' || userName === null) {
    alert('Canceled');
} else {
    alert("I don't know you");
}

0개의 댓글