# 07_JavaScript: short-circuit evaluation

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

Ex01. Sample Code

```javascript
const dog = {
    name: 'siru';
};

function getName(animal) {
    return animal.name;
}

const name = getName(dog); // There is a parameter
console.log(name); //siru
```

\-&gt; What if there is no proper parameter?

```javascript
const dog = {
  name: 'siru';
};

function getName(animal) {
  return animal.name; //Error(The animal object is undefined)
}

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

\-&gt; Solution01 : using if

```javascript
const dog = {
  name: 'siru';
};

function getName(animal) {
    if (animal) { //check animal 
        return animal.name;
    }
    return undefined;
}

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

\-&gt; Solution02 : using &&

```javascript
const dog = {
  name: 'siru';
};

function getName(animal) {
    return animal && animal.name; // If animal is truthy, use animal.name
}

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

```javascript
const dog = {
  name: 'siru';
};

function getName(animal) {
    return animal && animal.name; // If animal is truthy, use animal.name
}

const name = getName(dog); // put parameter
console.log(name); //siru
```

---

Ex02. Sample Code

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

function getName(animal) {
    const name = animal && animal.name;
    if (!name) {
        return 'no name dog';
    }
    return name;
}
const name = getName(namelessDog);
console.log(name); //no name dog
```

\-&gt; Make it shorter using the || operator

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

function getName(animal) {
    const name = animal && animal.name;
    return name || 'no name dog'; //if name is falsy, use 'no name dog'
}
const name = getName(namelessDog);
console.log(name); //no name dog
```

---

Ex03. Sample code : Calculate Circle Area

```javascript
function calculateCircleArea(r) {
    return Math.PI * r * r; //Math.PI is π
}
const area = calculateCircleArea(4); // If there's no parameter here, console.log(area); will be NaN
console.log(area); // 50.26548245
```

\-&gt; If there's no parameter, set r=1

(ES5 ver.)

```javascript
function calculateCircleArea(r) {
    const radius = r || 1; //If there's no r, set radius=1
    return Math.PI * radius * radius;
}
const area = calculateCircleArea();
console.log(area); // 3.141592
```

(ES6 ver.)

```javascript
function calculateCircleArea(r = 1) { //set r = 1 first
    return Math.PI * r * r;
}
const area = calculateCircleArea();
console.log(area); // 3.141592
```

(Arrow function ver.)

```javascript
const calculateCircleArea = (r = 1) => Math.PI * r * r;

const area = calculateCircleArea();
console.log(area); // 3.141592
```

cf. [https://learnjs.vlpt.us/useful/03-short-circuiting.html](https://learnjs.vlpt.us/useful/03-short-circuiting.html)
