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.


  • 2021-03-22 10:55:29

    box-shadow四个边框设置阴影样式

    其实对于box-shadow,老白我也是一知半解,之前用的时候直接复制已有的,也没有仔细思考过box-shadow的数值分别对应什么,最后导致阴影的边如何自由控制,苦于懒人一个一直没有正式去学习,今天无意中看到以下这篇文章,瞬间清醒有木有,看完整片文章,对于box-shadow阴影四个边的设置完全了如指掌了,再也不怕修改box-shadow了!

  • 2021-04-06 17:13:08

    nuxt.js keep-alive和嵌套路由不变化

    因为你错误的使用了 <nuxt>标签。 你应该使用 <nuxt-child keep-alive > </nuxt-child> 因为上层已经使用过了 <nuxt></nuxt>标签。

  • 2021-04-13 09:48:45

    消息中间件之MQ详解及四大MQ比较

    消息队列已经逐渐成为企业IT系统内部通信的核心手段。它具有低耦合、可靠投递、广播、流量控制、最终一致性等一系列功能,成为异步RPC的主要手段之一。当今市面上有很多主流的消息中间件,如老牌的ActiveMQ、RabbitMQ,炙手可热的Kafka,阿里巴巴自主开发RocketMQ等。