5

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

Community
  • 1
  • 1
alexey
  • 1,381
  • 9
  • 19
  • Just a hunch but could it be a timing thing? If you comment out `foo()` then `foo1` is printed. I do know that `console.log` some some strange thigns in the pipeline of logging if that makes sense. – ste2425 Mar 14 '16 at 12:07
  • Specifically a duplicate of http://stackoverflow.com/a/3721802/476 – deceze Mar 14 '16 at 12:07
  • @deceze then why does it run fine if `foo()` is commented out? – ste2425 Mar 14 '16 at 12:09
  • 1
    @ste2425 Say what now? Can you provide a fiddle for that statement/question? – deceze Mar 14 '16 at 12:11
  • @deceze yup https://jsfiddle.net/0gxw56xL/ – ste2425 Mar 14 '16 at 12:11
  • 1
    @ste2425 You've moved the opening brace to be on the same line as `return`. – James Thorpe Mar 14 '16 at 12:12
  • you reformated it, and that's the reason – alexey Mar 14 '16 at 12:12
  • 1
    Well aint that embarrassing, i never noticed sorry all, so used to clicking 'tidy'. – ste2425 Mar 14 '16 at 12:12
  • 1
    @ste2425 If you fix the exact issue that the question is about, well, yeah... – deceze Mar 14 '16 at 12:12
  • Your edit is quite a different question - you can use tools such as [jshint](http://jshint.com) (or jslint if you want to be really strict) - it will warn you about missing semicolons etc - paste your code above into that website to see. There are various ways you can automate running it. – James Thorpe Mar 14 '16 at 12:28
  • it is about to not allow running this, not get some warnings – alexey Mar 14 '16 at 12:30
  • You have to catch this at build time with a static analyser like jshint - you won't get it to throw errors, as it's technically valid code. – James Thorpe Mar 14 '16 at 12:40

2 Answers2

8

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.

Community
  • 1
  • 1
James Thorpe
  • 31,411
  • 5
  • 72
  • 93
2

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.

jtmarmon
  • 5,727
  • 7
  • 28
  • 45