Loading ...
Sorry, an error occurred while loading the content.

2746[jslint] Re: Ternary Indentation Question

Expand Messages
  • spence.randall@ymail.com
    Jan 18, 2012
      --- In jslint_com@yahoogroups.com, "Rob Richardson" <erobrich@...> wrote:
      >
      > --- In jslint_com@yahoogroups.com <mailto:jslint_com%40yahoogroups.com> ,
      > douglascrockford wrote:
      >
      > --- In jslint_com@yahoogroups.com <mailto:jslint_com%40yahoogroups.com> ,
      > "spence.randall@" <randall@> wrote:
      >
      > > Given the following example code:
      > >
      > > function test(x) {
      > > ~~~~'use strict';
      > > ~~~~return x === 1 ? 'one' :
      > > ~~~~~~~~x === 2 ? 'two' :
      > > ~~~~~~~~~~~~x === 3 ? 'three' :
      > > ~~~~~~~~~~~~~~~~x === 4 ? 'four' : 'zero'; }
      >
      > > I would write it this way:
      >
      > > function test(x) {
      > ~~~~'use strict';
      > ~~~~return x === 1
      > ~~~~~~~~? 'one'
      > ~~~~~~~~: x === 2
      > ~~~~~~~~? 'two'
      > ~~~~~~~~: x === 3
      > ~~~~~~~~? 'three'
      > ~~~~~~~~: x === 4
      > ~~~~~~~~? 'four'
      > ~~~~~~~~: 'zero';
      > }
      >
      > > The placement of ? and : makes it easier to read them as then and else if.
      >
      > If the point is clarity, this is much clearer:
      >
      > function test(x) {
      > ~~~~'use strict';
      > ~~~~var y = 'zero';
      > ~~~~switch(x) {
      > ~~~~~~~~case 1:
      > ~~~~~~~~~~~~y = 'one';
      > ~~~~~~~~~~~~break;
      > ~~~~~~~~case 2:
      > ~~~~~~~~~~~~y = 'two';
      > ~~~~~~~~~~~~break;
      > ~~~~~~~~case 3:
      > ~~~~~~~~~~~~y = 'three';
      > ~~~~~~~~~~~~break;
      > ~~~~~~~~case 4:
      > ~~~~~~~~~~~~y = 'four';
      > ~~~~~~~~~~~~break;
      > ~~~~~~~~default:
      > ~~~~~~~~~~~~y = 'zero';
      > ~~~~~~~~~~~~break; // Technically not needed
      > ~~~~}
      > ~~~~return y;
      > }
      >
      > After making this change, JSLint will note that "switch" and "case" should
      > be at the same indentation level.
      >
      > Rob
      >

      Thanks Rob, I agree switch makes more sense, but the question was on the indention expected, not the function itself. I just quickly created that one to illustrate JSLint's message.

      -Randall
    • Show all 8 messages in this topic