LoginSignup
0
0

More than 1 year has passed since last update.

null, undefined, NaNの違い

Last updated at Posted at 2023-03-02

TypeScript には「値がない」という状態の表現として nullundefinedのふたつが存在します。
さらに、返す数値が存在しない表現として NaN があります。
これらの違いについてのまとめです。

null とは

  • TypeScript のプリミティブ1のひとつ
    • ただし typeof では object を返す2
      console.log(typeof(null)); // "object"
      
  • 値がないという状況
  • プリミティブなので null という型も存在する
     const x:null = null;
    

undefined とは

  • TypeScript のプリミティブのひとつ
    console.log(typeof(undefined)); // "undefined"
    
  • 値が未定義という状況
  • プリミティブなので undefined という型も存在する
     const x:undefined = undefined;
    

NaN とは

  • NaN は Number 型に存在する特殊な値
    console.log(typeof(NaN)); // "number"
    
  • 数値が必要な場面で数値が得られなかった場合に出現
  • 数値を表すものではない
  • NaN を含んだ等価演算式、比較演算子では必ず false を返す
    const x = NaN;
    console.log(x === 100); // false
    console.log(x > 100); // false
    console.log(x < 100); // false
    // === で NaN を判定することもできない
    console.log(x === NaN); // false
    
  • NaN の判定するには Number.isNaN() を使用する
    const x = NaN;
    console.log(Number.isNaN(x)); // true
    

TypeScript では null と undefined のどちらを使うべきなのか?

TypeScript のコーディング・ガイドライン では undefined の使用を推奨しています。

参考

  1. プリミティブとは、TypeScript における基本的な値で、string, number, boolean, bigint, null, undefined, symbol がある

  2. JavaScript の初期からの実装に基づく

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0