【JavaScrpipt】データ型

に公開

真偽値 true false

  • falsyな値: false, 0, -0, NaN, '', undefined, null
  • truthyな値: false以外の全て。ture, 間違いやすいのは、' '(空文字), [](配列), {}(オブジェクト)
let isDevMode = true;
const pElement = document.querySelector('p');
const buttonElement = document.querySelector('button');

buttonElement.addEventListener('click', () => {

    // 早期リターン。if演算子なので真偽値を省略。否定の「!」でfalse
    if (!confirm('切り替えて良いですか?')) {
    // 下記のif文と同様。
    // if (confirm('切り替えて良いですか?') === false) {
        return;
    }

    if (isDevMode === true) { // if演算子は、暗黙的に真偽値が入ることが期待されていて、定数/変数名のみでも良い。if (isDevMode) {
        pElement.textContent = '通常モード';
        // isDevMode = false;
    } else {
        pElement.textContent = '開発者モード';
        // isDevMode = true;
    }
    isDevMode = !isDevMode; // 各条件それぞれでのisDevMode = 〇〇が不要になる
});

undefined

  • 宣言されただけの変数/定数、存在しない配列のインデックス、存在しないオブジェクトのプロパティは、undefined になるのでfalsyな値
const score = {math: 33, english: 77};
// console.log(score.sience);
if (score.sience === undefined) {
    console.log('科学は定義されていません');
}

null

const score = {
    math: 33, 
    english: 77,
    sience: null, // 科目は定義したいが、点数データはまだない等、明示したい場合
};
if (score.sience === null) {
    console.log('科学の点数はありません');
}

'use strict';

{
  // typeof
  console.log(typeof 1); // number
  console.log(typeof 'text'); // string
  console.log(typeof [1, 4]); // object(JSでは配列はオブジェクトの一部)
  console.log(typeof {math: 80, english: 90}); // object
  console.log(typeof true); // boolean
  console.log(typeof undefined); // undefined
  console.log(typeof null); // object(JSではnullはオブジェクトとされている)
}

Discussion