jstoolnpp icon indicating copy to clipboard operation
jstoolnpp copied to clipboard

New line before '{' option breaks JavaScript

Open esrat opened this issue 3 years ago • 6 comments

There is a nasty bug when using the option "New line before '{'"! This breaks the code being formatted when there are any return statements which do return structured data! E.g. "return {x:l, y:v}" will become

return
{
  x: l,
  y: v
}

When loading something like this in Firefox there will be an "Uncaught SyntaxError: unexpected token: ':'" for the y-attribute. So, after the format we got an empty return-statement. Changing the code to at least

return {
  x: l,
  y: v
}

will fix this issue. But of course this is no solution to have to search for all broken return-statements after every JSFormat.

So there have to be an exception for opening braces after the keyword return!

esrat avatar Nov 20 '21 00:11 esrat

I may consider disable this option.

sunjw avatar Nov 22 '21 01:11 sunjw

Oh, I do like this option! (I always choose it for every language I have to develop in - or at least to read and understand. It's much more convenient to have opening and closing braces at the same column in the source code!)

I do use your fine plug-in since years, to read and understand code - with this option enabled! Mostly, I have no need for active web development, so I never loaded formatted code (returning structured data) back to the browser - until two weeks ago.

I would really prefer to keep this option in the plug-in - and only apply the fix where it is necessary.

This whole problem only arises, because there is no necessity of a line ending semicolon in JavaScript. That’s why there is the automatic semicolon insertion (ASI, see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#automatic_semicolon_insertion) which enforces that in some special cases (like returning or throwing a structured expression) the opening brace is only allowed before the line break. Otherwise ASI will close the instruction by inserting a semicolon.

In all other cases the line break before the opening brace is perfectly fine.

esrat avatar Nov 29 '21 23:11 esrat

Sorry, I don't have enough time and test cases to guarantee the correctness of code formatted with this option. And I know some people like this option (which myself is one of them), but it seems JS has its own de facto standard of format. So, again, very sorry, but I will remove and disable this option in this plugin.

sunjw avatar Nov 30 '21 01:11 sunjw

Remove bracket in new line option related code. 74792b3590985d41157fc6f673bb4ada49d94f73

sunjw avatar Nov 30 '21 01:11 sunjw

Related to #20, #24, #90, #25, #128, #130

sunjw avatar Nov 30 '21 01:11 sunjw

If you need reference how it could be done in good quality without issues - you could see https://github.com/beautify-web/js-beautify/

Owyn avatar Jul 27 '22 10:07 Owyn