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

ESNext(いーえすねくすと)は、JavaScriptの次期バージョンを指す総称です。毎年新しい仕様がリリースされるECMAScriptの、まだ正式に承認されていない、開発中の機能を指すことが多いです。つまり、将来JavaScriptに実装される可能性のある、新しい構文やAPIなどを指します。✨

ESNextは、JavaScriptをより強力に、より便利にするための進化の最前線と言えますね! 💪

ESNextのサンプルコードと使用した場合・使用しなかった場合の比較 💡

ここでは、ESNextの代表的な機能の一つである「Null合体演算子 (Nullish Coalescing Operator) ??」を例に見てみましょう!


📌 サンプルコード (Null合体演算子 ?? の使用)

// 値がnullまたはundefinedの場合にのみデフォルト値を適用
const userName = null;
const displayName = userName ?? "ゲスト"; // userNameがnullなので"ゲスト"が代入される
console.log(displayName); // 出力: ゲスト

const age = 0;
const displayAge = age ?? 18; // ageは0なので0が代入される (0はnullでもundefinedでもない)
console.log(displayAge); // 出力: 0

const country = undefined;
const displayCountry = country ?? "日本"; // countryがundefinedなので"日本"が代入される
console.log(displayCountry); // 出力: 日本

📌 Null合体演算子 ?? を使用しない場合の比較

Null合体演算子がない場合、これまでは論理OR演算子 || や三項演算子を使用していました。

// 論理OR演算子 || を使用した場合
// || は、左辺がfalsyな値(false, 0, "", null, undefined, NaN)の場合に右辺を返すため、
// 0や空文字の場合にも意図せずデフォルト値が適用されてしまう可能性があります。
const userNameOld = null;
const displayNameOld = userNameOld || "ゲスト"; // userNameOldがnullなので"ゲスト"
console.log(displayNameOld); // 出力: ゲスト

const ageOld = 0;
const displayAgeOld = ageOld || 18; // ageOldが0(falsy)なので18が代入されてしまう
console.log(displayAgeOld); // 出力: 18 (意図しない結果)

const countryOld = undefined;
const displayCountryOld = countryOld || "日本"; // countryOldがundefinedなので"日本"
console.log(displayCountryOld); // 出力: 日本

console.log('---');

// 三項演算子を使用した例
const userNameTernary = null;
const displayNameTernary = (userNameTernary !== null && userNameTernary !== undefined) ? userNameTernary : "ゲスト";
console.log(displayNameTernary); // 出力: ゲスト

const ageTernary = 0;
const displayAgeTernary = (ageTernary !== null && ageTernary !== undefined) ? ageTernary : 18;
console.log(displayAgeTernary); // 出力: 0 (これは意図通り)

const countryTernary = undefined;
const displayCountryTernary = (countryTernary !== null && countryTernary !== undefined) ? countryTernary : "日本";
console.log(displayCountryTernary); // 出力: 日本

Null合体演算子 ?? は、null または undefined の場合にのみデフォルト値を適用するため、0 や空文字列 "" のような「falsy」な値でも、それが意図された値である場合には正しく扱えます。一方、論理OR演算子 || は、nullundefined だけでなく、0"" などもfalsyと見なしてデフォルト値を適用してしまうため、注意が必要です。 ⚠️

このように、ESNextの新しい機能は、コードをより簡潔に、そしてより意図通りに記述できるように進化していますね!これからも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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?