4

For some reason Visual Studio javascript formatting does not understand the syntax:

(function(){

})();

I'm getting "expected expression" in the second character of this line: })();

So I was wondering if anyone had this problem before (want to format their code but visual studio stubbornly thinks the valid code has an error and refuses to do so) and how do we solve it?

Adam Wagner
  • 15,469
  • 7
  • 52
  • 66
Namesis
  • 41
  • 1
  • 3
  • what kind of error is it giving you though? Technically, you're supposed to put the open/close parens right after the closing curly brace before the last closing curly brace. that could possibly be an error to the visual studio parser. – hellatan Jul 04 '11 at 13:30
  • i don't quite get you mate. btw i've updated my question to answer your question. – Namesis Jul 04 '11 at 13:51
  • 1
    I cannot reproduce this using VS 2010 Ultimate SP1. How are you getting this? Also, if you want to pass JSLint test, use this: `(function(){}());` – Mrchief Jul 04 '11 at 19:38
  • @namesis - Mrchief's example to pass jslint is what i meant – hellatan Jul 05 '11 at 15:01
  • Like @Dan said, looks like `(function(){` needs to be the first piece of code in the file to get the formatter to work. Even the JSLint conformant expression doesn't help if you have a leading semicolon before `(function(){`. – Oliver May 15 '13 at 10:24
  • Not just the compiler which doesn't know how it works - I don't either! – stewart99 Feb 17 '14 at 15:23

4 Answers4

3

It seems that in order to make the Visual Studio JS compiler happy, you need to have the "(function(){" be the first line of code in your .js file. You can precede it with comments/whitespace, if you'd like, but no code before it.

Sorry, I can't explain why it is that way but it should fix your problem.

Dan K
  • 31
  • 2
  • This seems to be the only way to get the javascript formatter to format the file again. Sad, as the leading semicolon was part of a jquery plugin template meant to guard against potential errors. – Oliver May 15 '13 at 10:22
1

Try the following:

(function () {

} ());

i.e., I've moved the function argument brackets inside the overall brackets.

stusmith
  • 14,003
  • 7
  • 56
  • 89
0

Use following shortcut:

ctrl k+d

sampathsris
  • 21,564
  • 12
  • 71
  • 98
0

I had to terminate all Node.exe tasks. After reopening my Javascript files, the ctrl+k,ctrl+d started working again. (Visual Studio 2017)

Erik Philips
  • 53,428
  • 11
  • 128
  • 150