本文へスキップ
BecomeCoder

JavaScriptのエラー · エラー1

Cannot read properties of undefined ― 無いものの中身を読んだ

存在しない値(undefined)のプロパティを読もうとしたときに出る、JavaScript で最も遭遇するランタイムエラーです。

出るコード

const user = { name: "Aoi" };
console.log(user.profile.age);   // profile は無い → undefined.age

エラーメッセージ

TypeError: Cannot read properties of undefined (reading 'age')

直し方

オプショナルチェーン user.profile?.age を使います。無いときの既定値は ?? 0 で用意します。そもそも値があるかを if (user.profile) で先に確認してもよいです。