LoginSignup
0
0

More than 3 years have passed since last update.

Uncaught TypeError: Cannot read property 'hoge' of undefined

Last updated at Posted at 2020-05-31

'〇〇' of Undefined

よく出くわすエラーなのですが、〇〇がundefinedで〇〇がおかしい!と私は早とちりしがちなので、
このエラーがどういう意味なのかということを残しておこうと思います。

マリオで見てみよう

こういうobjectがあるとします。

    const mario = {
      job: 'plumbing',
      relationship: {
        brother: 'Luige'
      }
    };

mario.hobbyだと、そんなプロパティはないので、undefinedになります。
image.png
ここまでは想像がつきますね。

cannot read property 'fire' of undefined

で、どんなふうに呼び出すとこのエラーがでるかというと、
mario.ability.fireとしたときです。
image.png

fire of undefinedなのでundefinedになっているfireではなく、
undefinedの中のfireというプロパティが読めないということですね。

marioの中のabilityというプロパティがなく、そこがundefinedになっているので、
undefinedの中のfireプロパティが読めないのです。

const mario = {
      job: 'plumbing',
      relationship: {
        brother: 'Luige'
      }
      undefined: {
        fire: 🔥
      }
    };

コードが複雑になってくると混乱してきますが、
こんなふうにシンプルに考えてみましょう。(と自分に言い聞かせている)

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