“Uncaught TypeError: undefined is not a function” in JavaScript code block

I have a JavaScript code block like below in my html page. When I run this by loading the page. I am getting below output on my browser console.

outer world 
Uncaught TypeError: undefined is not a function

As you can see in the code snippet, I am not executing the function named b anywhere in the code. But on running the code, the output from that function is coming along with an undefined is not a function error which I could not locate anywhere in my code block.

To add more to this scenario, there is no logs when I remove any one of the parts in the code. that is. If I remove b's initialization from the code then there are no errors and output. Also if I remove the self executing function block, there are no logs or errors. Its true that the b's initialization line is missing a semicolon. but what tempts it to provide such an output confuses me. Would you help me out to figure out a reasoning for this behaviour?

Can you please help me understand why it is happening so?

var b = function() {
  console.log('outer world');

(function() { 




Missed a ; after declaring b. The following code is equivalent to what you have.

var b = function() {
   console.log ('outer world');
}(function() {})();

Without the ; b becomes self-executing and takes an empty function as a parameter. After that it self-executes again; however, because b does not return a function, you get an exception.

I suggest not to skip ; until you become js ninja :). Keep b inside to avoid global scope pollution.

(function () {
    "use strict";

    var b = function () {
    // other code

Semicolon auto-insertion discussion

In case you do not want semicolons, add an operator before self-running function

var b = function () { console.log('outer world') }
;(function() { /* ... */ }())

ES6 Update:

(() => {
  const b = () => console.log('hi')
  // ...

You need a semicolon after your var declaration, and by the way, please remove the space between log and (

var b = function() {
       console.log('outer world');


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.