Bhumi Singhal
Bhumi Singhal

Reputation: 8307

Console.log does not work inside Self Executing Anonymous functions

(function() {
    console.log('Hello World');
})();

Does not print anything to console.

(function() {
    alert('Hello World');
})();

Gives an alert. Why so ?

Upvotes: -1

Views: 5601

Answers (2)

staleread
staleread

Reputation: 1

It seems like you don't see console logs at all. If using some sort of browser's dev tools you should select the displayed log levels.

I'm using Chrome's dev tools and your code works as expected with info log level enabled.

Screenshot

Upvotes: 0

Ayush Sharma
Ayush Sharma

Reputation: 2107

Both alert and console are working, please check when you are using console.log in self executing function, you are calling that function by using these brackets () or not. May be you are missing these in your code -

**Incorrect Code -** 
(function() {
    console.log('Hello World');
});
**Correct Code -** 
(function() {
console.log('Hello World');
})();

Correct code

enter image description here

Upvotes: 2

Related Questions