javascript エラー「Uncaught TypeError: console.log(…) is not a function」の解決方法

javascript エラー「Uncaught TypeError: console.log(…) is not a function」の解決方法

javascriptで、エラー「Uncaught TypeError: console.log(…) is not a function」が発生した場合の原因と解決方法を記述してます。

環境

  • OS windows11 pro 64bit
  • ブラウザ chrome 103.0.5060.134

エラー内容

以下の、三項演算子の前に値を確認する処理で発生。

function hoge( x , y ){

    console.log(x)

    ( x == 1 && y == 1 ) ? console.log('x and y 1') : console.log('no')

}

hoge( 1 , 1 )

エラーメッセージ

Uncaught TypeError: console.log(...) is not a function

画像

firefox102の場合は、以下のエラーが発生します。

Uncaught TypeError: console.log(...) is not a function

画像

safari15.5では、以下のエラーとなります。

TypeError: console.log(x)

     is not a function. (In 'console.log(x)

    ( x == 1 && y == 1 )', 'console.log(x)

    ' is undefined)

画像

原因

「;」がないと、改行しても同じステートメントと判断されるため。以下と同じになるため

console.log('a')()

解決方法

「;」をつけるか、

function hoge( x , y ){

    console.log(x);

    ( x == 1 && y == 1 ) ? console.log('x and y 1') : console.log('no')

}

hoge( 1 , 1 )

三項演算子の「括弧」を外す

function hoge( x , y ){

    console.log(x)

    x == 1 && y == 1 ? console.log('x and y 1') : console.log('no')

}

hoge( 1 , 1 )

ちなみに、「;」がないと、以下のコードでも同じようなエラーがでます。

function hoge( x , y ){

    let a = "yes"
    let b = "no"

    ( x === "a" && y == "b" ) ? console.log(a) : console.log(b)

}

hoge( "a" , "b" )
// Uncaught TypeError: "no" is not a function