Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS Strange behavior [duplicate]

Tags:

javascript

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

like image 384
alexey Avatar asked Mar 14 '16 12:03

alexey


2 Answers

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.

like image 193
James Thorpe Avatar answered Nov 08 '22 15:11

James Thorpe


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.

like image 45
jtmarmon Avatar answered Nov 08 '22 16:11

jtmarmon