LoginSignup
2
2

More than 1 year has passed since last update.

JavaScript初心者のためのエラーガイド

Posted at

1. Uncaught TypeError: Cannot read property 'b' of undefined at ...

解釋 : Undefinedのbというプロパティーを読めません。
例 :

a = undefined;
// undefined
a.b
// Uncaught TypeError: Cannot read property 'b' of undefined at ...

*ポイント : bではなく、aがundefinedです。


*対策1 :

if (a) {
a.b = ...
}
// aがundefinedでは無い時だけ、実行できます。

対策2 : Optional Chaining

c = a?.b;


2. Uncaught TypeError: Cannot read property 'b' of null at ...

例 :

a = null;
// null
a.b
// Uncaught TypeError: Cannot read property 'b' of null at ...

*ポイント : bではなく、aがnullです。


3. Uncaught TypeError: a.b is not a function at ...

例 :

a = {}
// {}
a.b()
// Uncaught TypeError: a.b is not a function at ...
console.log(a)
// {}
// undefined

*ポイント : オブゼットa内に、function bが無いこと。

*対策 :

Uncaught TypeError: a.b is not a function at ...と言うエラーが出た時は、console.log()で確認しましょう。


4. Uncaught ReferenceError: a is not defined at ...

例 :

let a, const a のように宣言してない時

import a from 'library';
const a = require('library');
のようにimport、requireの宣言してない時


4. Function位置に対する理解や注意点

例 :

setTimeout(() => {
console.log('hello');
}, 2000);
// 正しい : 予想通り、2秒後に'hello'を出力

setTimeout(function {
console.log('hello');
}, 3000);
// 正しい : 予想通り、3秒後に'hello'を出力

setTimeout(console.log('hello'), 4000);
// 正しく無い : 直ぐに'hello'を出力

window.addEventListener('click', () => {
console.log('hi'));
// 正しい : clickをすると'hi'を出力

window.addEventListener('click', console.log('hi'));
// 正しく無い : 直ぐに'hi'を出力

*ポイント :

window.addEventListener('click', console.log('hi'));

console.log('hi')は、Functionでは無いです。
Functionの呼び出しです。
つまり、Return値です。

もう少し説明すると、

console.log は、Functionです。
console.log() は、呼び出しです。Return値です。
// console.log()の値は、undefinedです。

下の2行のコードは、同じ意味です。

window.addEventListener('click', console.log('hi'));
window.addEventListener('click', undefined);

window.addEventListener('click', () => {});
// () => {}は、Functionです。
window.addEventListener('click', () => {}());
// 呼び出しためには、()を付けます。

setTimeout(console.log('hello'), 4000);
// console.log('hello')が実行されて、直ぐに'hello'を出力。
// その後、console.log('hello')はundefinedになります。

2
2
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
2
2