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

2017-09-03 20:12:31

Simply put a semicolon (;) after console.log().


Explanation

The error is easily reproducible like this:

It’s trying to pass function(){} as an argument to the return value of console.log() which itself is not a function but actually undefined (check typeof console.log();). This is because JavaScript interprets this as console.log()(function(){})console.log however is a function.

If you didn’t have the console object you’d see

ReferenceError: console is not defined

If you had the console object but not the log method you’d see

TypeError: console.log is not a function

What you have, however, is

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

Note the (...) after the function name. With those it’s referring to the return value of the function.


Respect the ;

All these code snippets result in all sorts of unexpected errors if no semicolons are present:

console.log() // As covered before() // TypeError: console.log(...) is not a functionconsole.log() // Accessing property 0 of property 1 of the return value…[1][0] // TypeError: console.log(...) is undefinedconsole.log() // Like undefined-3-3 // NaN

Another Example

You see the (...) oftentimes with the use of chained methods or chained property accessors:

string.match(/someRegEx/)[0]

If that RegEx isn’t found, the method will return null and the property accessor on null will cause a TypeError: string.match(...) is null — the return value is null. In the case of console.log(...) the return value was undefined.


  • 2020-05-07 13:42:13

    场景切换的集合移动,旋转,淡入淡出等

    两个场景(即两个div视图)切换的时候,如果想添加个过渡动画,除了可以使用js来实现,还可以通过CSS3的animation属性来实现。 (注意:Internet Explorer 9 以及更早的版本不支持 animation 属性。)

  • 2020-05-07 13:43:02

    css模拟开关按钮

    之前我们为大家分享过很多款各式各样的CSS3开关切换按钮,很多还是非常富有创意的,比如这里的多组超具创意的CSS3开关切换按钮和纯CSS3灯光开关动画。今天我们要带来另外一款外观很漂亮的纯CSS3开关切换按钮动画,它模拟了电灯的开关,并且在开和关之间切换时按钮的背景会有不同的变化,看起来非常不错。

  • 2020-05-07 18:40:35

    CSS让页面平滑滚动

    凡是需要滚动的地方都加一句scroll-behavior:smooth就好了!

  • 2020-05-12 10:17:07

    createElementNS和createElement区别

    指定与元素相关联的命名空间URI的字符串。创建的元素的namespaceURI属性使用namespaceURI的值进行初始化。 参见有效的命名空间URL。