1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

あまり知られていないけど便利なJavaScriptの書き方Tips

Posted at

オプショナルチェイニング(?.)とNull合体演算子(??)

オブジェクトの深いプロパティを安全に参照する際に便利なのがオプショナルチェイニングです。obj?.propのように書くと、途中がnullundefinedでもエラーを出さずにundefinedを返してくれます。さらにNull合体演算子??を組み合わせれば、obj?.prop ?? 'デフォルト値'のように簡潔にデフォルト値を設定できます。

分割代入とデフォルト値

オブジェクトや配列から値を取り出す際、デフォルト値を指定することで存在しないプロパティでも安全に扱えます。

const { name = '匿名', age = 0 } = user;
const [first = 0, second = 0] = arr;

スプレッド・レスト演算子

オブジェクトや配列のコピー・結合や可変長引数の受け取りが簡潔に書けます。

const newObj = { ...oldObj, updated: true };
function sum(...args) { return args.reduce((a, b) => a + b, 0); }

タグ付きテンプレートリテラル

テンプレートリテラルに独自関数を紐付けて、文字列のエスケープや整形を柔軟に行えます。

function safe(strings, ...values) { /*...*/ }
safe`SELECT * FROM users WHERE name = ${username}`;

まとめ

ES2020以降で導入されたこれらの構文を活用すると、コードの安全性や可読性が向上します。実際の開発でも積極的に取り入れてみてください。

1
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?