Solve - console.log(...) is not a function Error in JS

avatar

Borislav Hadzhiev

Wed Oct 20 20212 min read

banner

Photo by Iswanto Arif

Solve - console.log(...) is not a function Error #

The "console.log(...) is not a function" error occurs for multiple reasons:

  • Forgetting to place a semicolon between the console.log call and an IIFE.
  • defining a variable named console in your code.

typeerror console log is not a function

Here are the two most common ways the error occurs.

index.js
console.log('Test') // ๐Ÿ‘ˆ๏ธ forgot semicolon // โ›”๏ธ TypeError: console.log is not a function (function() {}) const console = 'hello'; // ๐Ÿ‘ˆ๏ธ defined console variable // โ›”๏ธ TypeError: console.log is not a function console.log('Test');

In the first example we forgot to place a semicolon between the call to the console.log method and an immediately invoked function expression.

The result of this is - we basically call the return value of the console.log method, which is undefined.

index.js
console.log('Test')()

To solve the "console.log is not a function" error, make sure to place a semicolon between your console.log call and an immediately invoked function expression and don't define any variables named console in your code.

index.js
console.log('Test'); // ๐Ÿ‘ˆ๏ธ forgot semicolon // โœ… Works (function() {})

The second cause of the error is defining a variable named console in your code.

If for some reasons you have to do that, you can access the native console.log method on the window object if you're in the browser, or on the global object if you're in Node.js.

index.js
// โœ… Works in browser window.console.log('Test'); // โœ… Works in Node.js global.console.log('Test');

The console object is defined on the window object if you're in the browser, and on the global object, if you're in Node.js.

Note that it's a bad practice to define a variable that shadows a native object, however sometimes 3rd party packages do this and you have no other way to access the native object, other than the window or global variables.

In short, the "is not a function" error means that the value you're trying to invoke is not a function.

The most common reasons this error occurs are:

  • defining a variable with the same name, that shadows the original object.
  • calling a method on a value of a different type, e.g. calling the Array.map method on an object.
  • misspelling the method - all method names are case sensitive in JavaScript.
  • placing a second set of parenthesis after calling any method, e.g. console.log('test')().

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee