モダンな JS 記法メモ:import / export と `?.` / `??`
· 5 min read
TypeScript / React / Next.js をやる前提で、「最低限これだけ押さえておきたい」モダン JS 記法のうち、
- ES Modules(
import/export) - オプショナルチェイニング
?. - Null 合体演算子
??
について、自分用にざっと整理したメモ。
1. ES Modules(import / export)
1-1. named export / import(名前付き)
書き出す側:
// math.js
export function add(a, b) {
return a + b;
}
export function sub(a, b) {
return a - b;
}
読み込む側:
// main.js
import { add, sub } from "./math.js";
console.log(add(1, 2)); // 3
console.log(sub(5, 3)); // 2
ポイント:
exportした関数・定数を 波カッコ{ ... }で名前指定して import する- 名前は基本そのまま使うが、
asでリネームもできる
import { add as plus } from "./math.js";
plus(1, 2);
1-2. default export / import(そのファイルの「メイン」)
書き出す側:
// calc.js
export default function calc(a, b) {
return a + b;
}
読み込む側:
// main.js
import calc from "./calc.js";
calc(1, 2);
ポイント:
defaultは 1ファイルに1つだけ- import 側は
{}なしで OK(名前も自由につけてよい)
React コンポーネントだとよくあるパターン:
// Button.jsx
export default function Button() {
return <button>Click</button>;
}
// page.jsx
import Button from "./Button";
export default function Page() {
return <Button />;
}
1-3. 自分の理解整理
export…「このファイルの外から使えるようにする」import…「別ファイルのexport済みのものを読み込む」- named export …
{ name }で複数出し入れ - default export … そのファイルの「メイン」1つだけ
2. オプショナルチェイニング ?.
ネストしたプロパティを安全に参照するための記法。
2-1. 従来の書き方
const city =
user && user.address
? user.address.city
: undefined;
user や user.address が undefined のときに、
user.address.city がエラーにならないようにガードを書いていた。
2-2. ?. を使う書き方
const city = user?.address?.city;
意味:
userがnull/undefined→ その時点でundefinedを返すuser.addressがnull/undefined→ その時点でundefinedを返す- それ以外 → 普通に
user.address.cityを返す
例:
const user = { name: "rinta" };
const city = user.address?.city;
console.log(city); // undefined(エラーにはならない)
3. Null 合体演算子 ??
「null / undefined のときだけデフォルト値を使う」演算子。
3-1. || との違い
const value1 = 0 || 100; // 100(0 は falsy 扱い)
const value2 = 0 ?? 100; // 0 (0 はそのまま有効な値)
||は「falsy(0, "", false など)」なら右側を採用??は「null/undefinedのときだけ」右側を採用
3-2. よくあるパターン
const input = undefined;
const value = input ?? "デフォルト";
console.log(value); // "デフォルト"
4. ?. と ?? の組み合わせ
一緒に使うと「安全に辿る+デフォルト値」が一行で書ける。
const user = { name: "rinta" };
const city = user.address?.city ?? "不明";
console.log(city); // "不明"
流れ:
user.addressはundefineduser.address?.cityはundefinedを返す(エラーにならない)undefined ?? "不明"→ "不明" を採用
別パターン:
const user2 = { name: "Alice", address: { city: "Tokyo" } };
const city2 = user2.address?.city ?? "不明";
console.log(city2); // "Tokyo"
5. まとめ(自分用の一言メモ)
-
import/export- ファイル間でコードをやりとりする仕組み
- named export …
{ foo, bar }で複数 - default export … 1ファイルに1つのメイン
-
?.null/undefinedかもしれない中身を安全にたどる- ダメなら即
undefinedを返してくれる
-
??- 左が
null/undefinedのときだけ右側の値を使う 0,"",falseなどはちゃんと有効な値として扱われる
- 左が
TypeScript / React / Next.js のコードを読むとき、 この3つはかなりの頻度で出てくるので、「省略前の姿」とセットで覚えておく。