# 論理演算子

複数の関係演算子や真偽値等を組み合わせる演算子を**論理演算子**といい、`&&`,`||`,`!`が該当します。

`&&`は左右の式が共に`true`の場合に`true`を返却します。

もう少し内部的な処理の話をすると、

**左側を実行してfalseの場合、右側が実行されません。**

**左側がtrueの場合、右側が実行されます。**

<pre class="language-javascript" data-title="index.js◎"><code class="lang-javascript">...
console.log(userType);

// xは10
<strong>console.log(x > 5 &#x26;&#x26; x &#x3C; 20); // 左右ともにtrueのため、true
</strong><strong>console.log(x > 15 &#x26;&#x26; x &#x3C; 20); // 左側がfalseのため、false
</strong><strong>console.log(x > 5 &#x26;&#x26; x &#x3C; 9); // 右側がfalseのため、false
</strong>
</code></pre>

`||`は左右の式の片方がtrueの場合に`true`を返却します。

こちらは

**左側を実行してfalseの場合、右側を実行します。**

**左側がtrueの場合、右側は実行されません。**

<pre class="language-javascript" data-title="index.js◎"><code class="lang-javascript">...
console.log(x > 5 &#x26;&#x26; x &#x3C; 9); // 右側がfalseのため、false

<strong>console.log(x > 5 || x &#x3C; 9); // 左側がtrueのため、true
</strong><strong>console.log(x > 16 || x &#x3C; 20); // 右側がtrueのため、true
</strong><strong>console.log(x > 16 || x &#x3C; 9); // 左右ともにfalseのため、false
</strong></code></pre>

`!`は後に続く条件式や真偽値を反転させます。

<pre class="language-javascript" data-title="index.js◎"><code class="lang-javascript">...
console.log(x > 16 || x &#x3C; 14); // 左右ともにfalseのため、false

<strong>console.log(!(x > 16)); // 条件式はfalseであるが、反転してtrueとなる
</strong></code></pre>

少し話は変わりますが、**Truthy、Falsyな値**に関して説明します。

**Truthy、Falsyな値**とは任意な値を強制的に論理型に変換することです。

**Falsyな値**は以下が該当します。

* undefined
* null
* 0
* false
* ''（空文字）
* NaN

上記以外は**Truthyな値**になります。

上記を考慮すると、真偽値以外の値も使用することでき、`true`となる場合は、その使用した値を返却することができます。

<pre class="language-javascript" data-title="index.js◎"><code class="lang-javascript">...
console.log(!(x > 16)); // 条件式はfalseであるが、反転してtrueとなる
<strong>console.log(true &#x26;&#x26; 'a'); // 左側がtrueなため、右側も実行され、truthyな値のため"a"が返却される
</strong><strong>console.log(false &#x26;&#x26; 'a'); // 左側がfalseのため、右側は実行されない
</strong><strong>console.log(true || 1); // 左側がtrueなため、右側は実行されない
</strong><strong>console.log(false || 1); // 左側がfalseのため、右側も実行され、truthyな値なため1が返却される
</strong></code></pre>
