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() { })();
A variable that has not been assigned a value is of type undefined . A method or statement also returns undefined if the variable that is being evaluated does not have an assigned value. A function returns undefined if a value was not returned .
According to the Mozilla website for developer documents, “the TypeError object represents an error when a value is not of the expected type.” Uncaught means that the error was not caught in the catch part of the try-catch block.
This is a standard JavaScript error when trying to call a function before it is defined. This error occurs if you try to execute a function that is not initialized or is not initialized correctly. This means that the expression did not return a function object.
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 () { console.log("hi"); }; // 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') // ... })()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With