Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. The Lounge
  3. Javascript brace style - THAT discussion probably again

Javascript brace style - THAT discussion probably again

Scheduled Pinned Locked Moved The Lounge
csharpquestionjavascriptpythonhtml
31 Posts 21 Posters 21 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • J jsc42

    TOOTBS (aka K&R) is only about layout of statements. It gets confused with object literals purely because they use braces but for an entirely different purpose; same as '(' and ')' have multiple uses, as does the ','. That, combined with the lazy end of statement convention, is the only rationale for using TOOTBS. But you can use logical aligned braces even when returning objects either by making them subexpressions (using one of the alternative uses of '(' and ')') or by converting the object to a named object. Viz:

    return (
    {
    p1: 1,
    p2: 2
    });
    // or (my preference)
    var result =
    {
    p1: 1,
    p2: 2
    };

    return result;

    J Offline
    J Offline
    Jeremy Falcon
    wrote on last edited by
    #22

    Btw, when we say object literal in a return statement, that explicitly implies to not use a variable. Which is the entire point of what we're talking about. What is literal? Webopedia Definition[^]

    Jeremy Falcon

    1 Reply Last reply
    0
    • M Marc Clifton

      So, I force myself to write Javascript with this brace style, since it seems that that's what is the "correct" style (example):

      function ajaxError(data) {
      alertBad(data);
      }

      But then I see this [HTML5 WebSockets](https://www.tutorialspoint.com/html5/html5\_websocket.htm) and their example uses the style I'm used to in C#. So which is the "approved / standard / whatever" style? What style do you use: 1: Javascript style as per example? 2: Braces on separate lines style?

      Latest Article - Class-less Coding - Minimalist C# and Why F# and Function Programming Has Some Advantages Learning to code with python is like learning to swim with those little arm floaties. It gives you undeserved confidence and will eventually drown you. - DangerBunny Artificial intelligence is the only remedy for natural stupidity. - CDP1802

      E Offline
      E Offline
      EbenRoux
      wrote on last edited by
      #23

      Perhaps someone has mentioned this but haven't read *all* the responses :) There is actually a bit of a caveat with JS: it terminate some lines automatically (like an invisible semi-colon) Open your browser and go to the dev-tools (typically F12) and enter the following:

      var f1 = function() {
      return {
      value: 'the-value'
      };
      }

      var f2 = function() {
      return
      {
      value: 'the-value'
      };
      }

      Now have it execute

      f1()

      and then

      f2()

      . You'll quickly see the difference :) It is better to stick with the "standard" with braces on the same line. For my C# code it's is quite different.

      1 Reply Last reply
      0
      • M Marc Clifton

        So, I force myself to write Javascript with this brace style, since it seems that that's what is the "correct" style (example):

        function ajaxError(data) {
        alertBad(data);
        }

        But then I see this [HTML5 WebSockets](https://www.tutorialspoint.com/html5/html5\_websocket.htm) and their example uses the style I'm used to in C#. So which is the "approved / standard / whatever" style? What style do you use: 1: Javascript style as per example? 2: Braces on separate lines style?

        Latest Article - Class-less Coding - Minimalist C# and Why F# and Function Programming Has Some Advantages Learning to code with python is like learning to swim with those little arm floaties. It gives you undeserved confidence and will eventually drown you. - DangerBunny Artificial intelligence is the only remedy for natural stupidity. - CDP1802

        J Offline
        J Offline
        John Bevan
        wrote on last edited by
        #24

        Generally follow the standards / style guide at your place of work. However, with JavaScript there can be gotchas; due to semicolons being optional, as per this example: javascript - Why does a results vary based on curly brace placement? - Stack Overflow[^] So you have to be cautious that in such cases you use the code that works over the dictated style; and put a comment so no one decides to clean up your formatting not realising that they're introducing a bug. If you're defining a style, I'd say it's best to pick one which avoids this issue, so going with some variant of K&R makes sense for this language, to avoid such pitfalls & any cognitive load related to spotting them. For most other languages (i.e. where placement is solely formatting), I'd typically recommend Allman style for clarity (personal preference); though I may suggest K&R for any projects where the same developers are likely to work with JavaScript; again so they don't have to think about it (i.e. when switching languages). Regarding my personal preference; historically I was a K&R advocate, but later realised that the Allman style allows lining up the open and close brackets, which is more obvious than lining up the code responsible for the bracket. Once you develop the habit of thinking "the line before the open brace is the one defining this block" rather than "the first line of the block defines the block & ends with the opening brace" it pays off. You do use up more screen real estate; but often (at least for developers with large monitors), that's good, since it removes clutter.

        1 Reply Last reply
        0
        • N Nemanja Trifunovic

          Be careful! With JavaScript, it is not just a matter of style[^]. Just use the K&R style or you may introduce subtle bugs. Plus, K&R is the only true style :-D

          utf8-cpp

          G Offline
          G Offline
          Gary Wheeler
          wrote on last edited by
          #25

          Nemanja Trifunovic wrote:

          it is not just a matter of style[^]

          That is utterly disgusting. An interpreter that changes programmer intent based upon white space can't be trusted.

          Nemanja Trifunovic wrote:

          K&R is the only true style

          I was a K&R true believer for a long time. I like white space (line breaks) in my code to delineate things. When I started writing in C#, I discovered that Allman style[^] reduced the number of line breaks while retaining the visual separation.

          Software Zen: delete this;

          D J 2 Replies Last reply
          0
          • G Gary Wheeler

            Nemanja Trifunovic wrote:

            it is not just a matter of style[^]

            That is utterly disgusting. An interpreter that changes programmer intent based upon white space can't be trusted.

            Nemanja Trifunovic wrote:

            K&R is the only true style

            I was a K&R true believer for a long time. I like white space (line breaks) in my code to delineate things. When I started writing in C#, I discovered that Allman style[^] reduced the number of line breaks while retaining the visual separation.

            Software Zen: delete this;

            D Offline
            D Offline
            Dan Neely
            wrote on last edited by
            #26

            Gary Wheeler wrote:

            That is utterly disgusting. An interpreter that changes programmer intent based upon white space can't be trusted.

            There's a reason why so many of us loathe javascript. X|

            Did you ever see history portrayed as an old man with a wise brow and pulseless heart, weighing all things in the balance of reason? Is not rather the genius of history like an eternal, imploring maiden, full of fire, with a burning heart and flaming soul, humanly warm and humanly beautiful? --Zachris Topelius Training a telescope on one’s own belly button will only reveal lint. You like that? You go right on staring at it. I prefer looking at galaxies. -- Sarah Hoyt

            G 1 Reply Last reply
            0
            • D Dan Neely

              Gary Wheeler wrote:

              That is utterly disgusting. An interpreter that changes programmer intent based upon white space can't be trusted.

              There's a reason why so many of us loathe javascript. X|

              Did you ever see history portrayed as an old man with a wise brow and pulseless heart, weighing all things in the balance of reason? Is not rather the genius of history like an eternal, imploring maiden, full of fire, with a burning heart and flaming soul, humanly warm and humanly beautiful? --Zachris Topelius Training a telescope on one’s own belly button will only reveal lint. You like that? You go right on staring at it. I prefer looking at galaxies. -- Sarah Hoyt

              G Offline
              G Offline
              Gary Wheeler
              wrote on last edited by
              #27

              It's stuff like this that reminds me to be glad I don't do web programming.

              Software Zen: delete this;

              1 Reply Last reply
              0
              • M Marc Clifton

                So, I force myself to write Javascript with this brace style, since it seems that that's what is the "correct" style (example):

                function ajaxError(data) {
                alertBad(data);
                }

                But then I see this [HTML5 WebSockets](https://www.tutorialspoint.com/html5/html5\_websocket.htm) and their example uses the style I'm used to in C#. So which is the "approved / standard / whatever" style? What style do you use: 1: Javascript style as per example? 2: Braces on separate lines style?

                Latest Article - Class-less Coding - Minimalist C# and Why F# and Function Programming Has Some Advantages Learning to code with python is like learning to swim with those little arm floaties. It gives you undeserved confidence and will eventually drown you. - DangerBunny Artificial intelligence is the only remedy for natural stupidity. - CDP1802

                W Offline
                W Offline
                who_me 0
                wrote on last edited by
                #28

                The obsessive compulsive in me hates the 'brace on same line' style. It feels like you're deliberately starting something on the end of a sentence. Start a statement/block at the start of a line, that's easiest for most of us to read. I think. (If that paragraph was a little harder to read than normal, my point is made). There's a good case for the vertical compression that the K&R style offers, showing more code on screen at the same time makes it easier for the reader to take in more at once. Ideally, he/she should be able to see any function/method onscreen at once. Conversely, if you have nested blocks, I find the Allman style far clearer in determining which brackets match with which. Ideally the editor would just display according to the preferences of the viewer, but as per the js example above, it's probably not always feasible. I don't know if source-comparison tools are smart enough to determine "nothing changed apart from indentation/non-printing characters, so mark nothing as changed".

                1 Reply Last reply
                0
                • G Gary Wheeler

                  Nemanja Trifunovic wrote:

                  it is not just a matter of style[^]

                  That is utterly disgusting. An interpreter that changes programmer intent based upon white space can't be trusted.

                  Nemanja Trifunovic wrote:

                  K&R is the only true style

                  I was a K&R true believer for a long time. I like white space (line breaks) in my code to delineate things. When I started writing in C#, I discovered that Allman style[^] reduced the number of line breaks while retaining the visual separation.

                  Software Zen: delete this;

                  J Offline
                  J Offline
                  joebrown org uk
                  wrote on last edited by
                  #29

                  Disgusting it most certainly is, but it's one of the rules (features, idiocies..) of the language. For something really disgusting try Python, where white space starts and finishes blocks - depending on how many spaces. I use Python, but hate the fascist insistence on the use of white space. I'm comfortable with Javascript, but slavishly terminate statements myself - rather than letting the interpreter/compiler. I have more, much more problems with Python, than Javascript.

                  1 Reply Last reply
                  0
                  • M Marc Clifton

                    So, I force myself to write Javascript with this brace style, since it seems that that's what is the "correct" style (example):

                    function ajaxError(data) {
                    alertBad(data);
                    }

                    But then I see this [HTML5 WebSockets](https://www.tutorialspoint.com/html5/html5\_websocket.htm) and their example uses the style I'm used to in C#. So which is the "approved / standard / whatever" style? What style do you use: 1: Javascript style as per example? 2: Braces on separate lines style?

                    Latest Article - Class-less Coding - Minimalist C# and Why F# and Function Programming Has Some Advantages Learning to code with python is like learning to swim with those little arm floaties. It gives you undeserved confidence and will eventually drown you. - DangerBunny Artificial intelligence is the only remedy for natural stupidity. - CDP1802

                    D Offline
                    D Offline
                    Dimitrios Kalemis
                    wrote on last edited by
                    #30

                    Yes, it is the "correct" style for Javascript, even though I hate using it. When I program in other languages, I always use a new line for a brace, either opening brace or closing brace. But in Javascript, if you use the opening brace in a new line, Javascript may automatically insert a semicolon in the previous line. Try searching the Internet about this "feature". For example, you may consult javascript - Why does a results vary based on curly brace placement? - Stack Overflow[^]

                    1 Reply Last reply
                    0
                    • M Marc Clifton

                      So, I force myself to write Javascript with this brace style, since it seems that that's what is the "correct" style (example):

                      function ajaxError(data) {
                      alertBad(data);
                      }

                      But then I see this [HTML5 WebSockets](https://www.tutorialspoint.com/html5/html5\_websocket.htm) and their example uses the style I'm used to in C#. So which is the "approved / standard / whatever" style? What style do you use: 1: Javascript style as per example? 2: Braces on separate lines style?

                      Latest Article - Class-less Coding - Minimalist C# and Why F# and Function Programming Has Some Advantages Learning to code with python is like learning to swim with those little arm floaties. It gives you undeserved confidence and will eventually drown you. - DangerBunny Artificial intelligence is the only remedy for natural stupidity. - CDP1802

                      O Offline
                      O Offline
                      obermd
                      wrote on last edited by
                      #31

                      The simple solution is to use a text editor that can be customized. The first thing I do to when I get a source code file is use my editor's auto-format feature to reformat the file to my preferences.

                      1 Reply Last reply
                      0
                      Reply
                      • Reply as topic
                      Log in to reply
                      • Oldest to Newest
                      • Newest to Oldest
                      • Most Votes


                      • Login

                      • Don't have an account? Register

                      • Login or register to search.
                      • First post
                        Last post
                      0
                      • Categories
                      • Recent
                      • Tags
                      • Popular
                      • World
                      • Users
                      • Groups