JS Strange Behavior

Can someone help me - why do we have this behavior in a JS snippet?

var foo = function() { return { hi: console.log("foo") } } var foo1 = function() { return { hi: console.log("foo1") } } foo(); foo1(); 

Why is only "foo" printed?

fiddle

EDIT ok, this is due to the automatic installation of the semicolon insert, BUT

Do we have some ways to make JS not execute these cases?

I mean, can we do something that will lead to an error here?

EDIT2

Looks like the best deal - JShint - I asked here

+5
source share
2 answers

You have applied JavaScript automatic semicolon insertion . Your second block is equivalent:

 var foo1 = function(){ return; { hi:console.log("foo1") } } 

IE, it does not return an object literal at all (and therefore console.log does not work) - it simply returns undefined .

+8
source

In foo1, the function returns before the object is evaluated. If you check the output of foo1() , it returns nothing. Therefore, most javascript style manuals suggest opening objects on the same line as the return keyword.

+2
source

Source: https://habr.com/ru/post/1245007/


All Articles