# 03. 단축 평가 논리 계산법

## 단축 평가 (short-circuit evaluation) 논리 계산법

이번에는 논리 연산자를 조금 더 유용하게 사용하는 방법에 대해서 배워보겠습니다.

우리가 이전에 연산자를 배울때, 다음과 사항을 잘 숙지하셨을겁니다.

```javascript
true && true  // true
true && false // false
true || false // true
false || true // true
```

논리 연산자를 사용 할 때에는 무조건 우리가 true 혹은 false 값을 사용해야 되는 것은 아닙니다. 문자열이나 숫자, 객체를 사용 할 수도 있고, 해당 값이 Truthy 하냐 Falsy 하냐에 따라 결과가 달라집니다.

```javascript
const dog = {
    name: '멍멍이'
};

var getName = function(animal) {
    if(animal){
        return animal.name;
    }
    return undefined;
}

const name = getName();
console.log(name);
```

getName()  //파라미터로 값이 없을때 **결과) undefined**

getName(dog)  //파라미터로 값이 있을때  **결과) 멍멍이**

### && 연산자로 코드 단축시키기

> A && B 연산자를 사용하게 될 때에는 **A 가 Truthy 한 값이라면, B 가 결과값**이 됩니다. \
> 반면, **A 가 Falsy 한 값이라면 결과는 A** 가 됩니다.

이렇게 코드를 작성해보세요.

```javascript
var getName = function(animal) {
    return animal && animal.name //위에 코드를 한줄로 작성한것이다.
}

const name = getName();
console.log(name); // undefined
```

이게 작동하는 이유는?

```javascript
console.log(true && 'hello');    // hello
console.log(false && 'hello');   // false
console.log('hello' && 'bye');   // bye
console.log(null && 'hello');    // null
console.log(undefined && 'hello'); //undefined
console.log('' && 'hello');       // ''
console.log(0 && 'hello');        // 0
console.log(1 && 'hello');        // hello
console.log(1 && 1);              // 1
```

이러한 속성을 잘 알아두면, **특정 값이 유효할때에만 어떤 값을 조회하는 작업을 해야 할 때 매우 유용합니다.**

### || 연산자로 코드 단축시키기

> **A || B 는 만약 A 가 Falsy한 값이면, B 가 결과값이 됩니다.** \
> **반면, A 가 Truthy 한 값이라면 B 가 됩니다.**

|| 연산자는 만약 어떤 값이 Falsy 하다면 대체로 사용 할 값을 지정해줄 때 매우 유용하게 사용 할 수 있습니다.

예를 들어서 다음과 같은 코드가 있다고 가정해봅시다.

```javascript
const namelessDog = {
  name: ''
};

function getName(animal) {
  const name = animal && animal.name;
  if (!name) {
    return '이름이 없는 동물입니다';
  }
  return name;
}

const name = getName(namelessDog);
console.log(name);  // 이름이 없는 동물입니다.
```

위 코드는 || 연산자를 사용하면 다음과 같이 단축시킬 수 있습니다.

```javascript
const namelessDog = {
  name: ''
};

function getName(animal) {
  const name = animal && animal.name;
  return name || '이름이 없는 동물입니다.';
}

const name = getName(namelessDog);
console.log(name); // 이름이 없는 동물입니다.
```

```javascript
console.log(false || 'hello');                   // hello
console.log('' || '이름없');                     // 이름없다.
console.log(null || '널이다~');                    // 널이다~
console.log(undefined || 'defined 되지 않았다!');   // defined 되지 않았다!
console.log(0 || '제로');                        // 제로다

console.log(1 || '음?');                           // 1
console.log(true || '여기 안본다.');                 // true
console.log('와아' || '여기 안봐요');                 // 와아
console.log([] || '노노');                         // []
```

### EX1)

```javascript
const dog = {
    name: '멍멍이'
};

const getName = function(animal) {
    return animal && animal.name;
};

const name = getName();     // undefined
const name = getName(dog);  // 멍멍이
console.log(name)

```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://triplexlab.gitbook.io/vanilla-js/02.vanilla-js/short-circuiting.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
