How should we indent `const` declarations?

kenbellows

Ken Bellows

Posted on January 10, 2019

How should we indent `const` declarations?

I'm a huge fan of the additions to JavaScript of let and const to declare block-scoped variables. In particular, I love const for the clarity of intention it gives developers. If this is a value that should never be changed, make it a const so everyone (including your future self) knows not to change it.

But I have a complaint: while let and its predecessor var are each 3 characters, const is 5 characters, which ruins indentation!

// var is 3 characters, which aligns nicely with a 4-space indentation style
var foo = 10,
    bar = 20,
    baz = 50;

// let keeps to the same 3 character pattern
let apples = 5,
    oranges = 30, // gotta get that citrus, no scurvy for me
    bananas = 12;

// const ruins everything!!!
const dontchangeme = 10,
    howmuchindentshouldihave = 4,
    thisfeelsverydirty = 0x0;

const doesn't allow for a nice alignment of variable names during declarations if you're used to 4-space indentation! I don't like the above default of just hitting enter and letting the indentation fall where it will, but I don't know what to do about it. Here are three options I'm considering:

  • Indent 6 spaces for const declarations - this is okay, but I hate that it breaks conformity with the surrounding code.
const foo = 10,
      bar = 20,
      baz = 30;
if (test) {
    console.log('Misaligned! 😢')
}
  • Write const repeatedly - a few of my coworkers have adopted this pattern; I'm not sold. It just seems unnecessarily verbose to me.
// seems like a lot of keywords...
const foo = 10;
const bar = 20;
const baz = 30;
  • Give const its own line - I've used this a bit, and it's alright, but still feels uncomfortable.
const
    foo = 10,
    bar = 20,
    baz = 30;

I need some feedback. What have you used? Which of these do you like/hate?

Another thought I had is that there's a crowd of developers out there that has sort of been dealing with the "declarations are 2 spaces more indented than everything else" problem for a while now: the 2-space indentation folks! What do you all do about this? Do you just indent 4 spaces for declarations, or... something else?

Awaiting responses!

💖 💪 🙅 🚩
kenbellows
Ken Bellows

Posted on January 10, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related