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-03-22 21:16:07

    用vue做的跟随鼠标移动的div

    最近接到一个任务,就是在既存用electron-vue开发的桌面端程序上追加随鼠标移动的动画效果,之前一直使用angular和react,没怎么接触过vue,先做一个vue的简单例子,然后再整合。

  • 2020-03-23 15:16:30

    import,require具体用法

    import 和 require 是JS模块化编程使用的,是前端开发者们在性能探索中的又一大进步。

  • 2020-03-30 15:37:12

    PM2下使用 npm run 命令

    npm run xxxx 是 node常用的启动方式之一,本文介绍下如何用PM2来实现该方式的启动。 下面是项目的package.json文件部分代码:

  • 2020-04-01 10:15:11

    vue-cli3.0中vue.config.js的基本配置(去除esLint提示和解决build后静态文件路径报错)

    vue-cli是开发vue项目必不可少的脚手架工具,3.0版本之前的目录结构是由config目录的,关于webpack配置的文件都放在该目录里面,而3.0版本之后做了一个大更新,webpack相关的默认配置都帮你集成到webpack的npm 包里面去了,官方提供的一种修改配置的方式就是开发者自己在项目的根目录(与src同层级的目录)下建立一个vue.config.js的文件,然后去覆盖自定义的配置,达到你想要的效果,下面写一个基本的默认配置