Can someone assist me - why we have this behavior in JS snippet?
var foo = function() {
return {
hi: console.log("foo")
}
}
var foo1 = function() {
return
{
hi: console.log("foo1")
}
}
foo();
foo1();
Why only "foo" is printed?
fiddle
EDIT ok, this is because of automatic semi-colon insertion, BUT
do we have some ways to force JS to not execute this cases?
I mean, can we do something that will throw error here?
EDIT2
Looks like best suggestion is JShint - i asked here
You've hit JavaScript's automatic semi-colon insertion. Your second block is the equivalent of:
var foo1 = function(){
return;
{
hi:console.log("foo1")
}
}
IE it's not returning the object literal at all (and so the console.log
isn't running) - it's just returning undefined
.
In foo1, the function returns before the object is evaluated. If you check the output of foo1()
it returns nothing This is why most javascript style guides suggest objects open on the same line as the return
keyword.
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