javascript エラー「Uncaught TypeError: Right-hand side of ‘instanceof’ is not an object」の解決方法

javascript エラー「Uncaught TypeError: Right-hand side of ‘instanceof’ is not an object」の解決方法

javascriptで、エラー「Uncaught TypeError: Right-hand side of ‘instanceof’ is not an object」が発生した場合の原因と解決方法を記述してます。「instanceof 」で右側に「”string”」などを指定した際に発生します。

環境

  • OS windows11 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 108.0.5359.125

エラー内容

以下のコードで発生。

"hoge" instanceof "string"

エラーメッセージ

Uncaught TypeError: Right-hand side of 'instanceof' is not an object

画像

firefox(バージョン107)では、以下のエラーとなります。

Uncaught TypeError: invalid 'instanceof' operand "string"

画像

safari(15.5)では、以下のエラーとなります。

TypeError: Right hand side of instanceof is not an object

画像

原因

右側に指定する値は、prototypeプロパティをもつ必要があるため

// instanceof使用例

function testClass() {}

let obj = new testClass();

console.log( obj instanceof testClass ); // true
console.log( obj instanceof Array );   // false

let arr = ["a", "b", "c"];

console.log( arr instanceof Array ); // true
console.log( arr instanceof testClass ); // false

解決方法

「string」を使用して型を判定する場合は、「typeof」を使用する

typeof "hoge" == "string"

実行結果