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.


  • 2018-01-17 01:55:49

    Android设置控件不可点击

    学会安卓控件的不可点击,再加上控件的透明度,估计你会做出不错的效果来。

  • 2018-01-17 15:58:16

    java实现定时任务的三种方法

    在进行多线程编程中,比较重要也是比较困难的一个操作就是如何获取线程中的信息。大多数人会采取比较常见的一种方法就是将线程中要返回的结果存储在一个字段中,然后再提供一个获取方法将这个字段的内容返回给该方法的调用者。如以下的ReturnThreadInfo类:

  • 2018-01-18 11:26:53

    浅谈js运行机制(线程)

    从开始接触js时,我们便知道js是单线程的。单线程,异步,同步,互调,阻塞等。在实际写js的时候,我们都会用到ajax,不管是原生的实现,还是借助jQuery等工具库实现,我们都知道,ajax可以实现局部刷新,并且在请求处理时,任然可以响应用户的操作,比如点击事件。不是说js是单线程吗?这些都是怎么实现的? 在阅读《深入理解Bootrap的源码》一书,在分析轮播组件(carousel.js)的源码时,作者对一句代码操作的注释引起了我的兴趣。