Why I use spaces over tabs

[UPDATE: I just got an email from someone saying they use tabs over spaces because visually aligning everything by repeatedly pressing the spacebar is too cumbersome. That is not what is meant by using spaces over tabs! Every IDE/editor supports replacing tab presses with a dynamic and variable number of spaces until you get to the appropriate indentation level. It would be insane if this misunderstanding turned out to be one of the cruxes of the issue.]


I never really understood the Tabs vs Spaces debate. When I first started programming I started using tabs but almost immediately realized they just weren’t suited for the job. They promise flexibility but, in practice, that flexibility is largely a lie and you tie other developers to your indentation style regardless. If you are tying developers in to a style, then why use tabs which can add unexpected confusion?

In the examples below, tab characters are colored a darker grey. Don’t get hung up on the coding style, the issues of alignment are what’s important and the code is terse for example’s sake.

Tabs with 4 char widths

This example shows an initial setup that uses a 4-width tab for nearly everything. It looks great and beautiful when you are set up for a 4-width tab, but try changing the tab width with the buttons below the example.


All the careful alignment goes to crap when you change the tab width. Yes, the fact that you can change the tab width is a great option to have, but if it requires you to reformat your code then it is not actually a real feature of using tabs, it’s the same situation in any scenario. Either manual or automatic reformatting all around.

Tabs with 2 char widths

Below is the same example as above, but optimized for a 2 character width tab. The exact same problem applies, but you can also see that it takes a different number of tabs to produce similar alignments.


Tabs for block indent only

The last entry on our tabstop tour is an example that only uses tabs for block level indentation, which some people use as a solution to the above problems. This still has its own issues when alignments occur across block level indentations (look at the last block) but also raises the simple question “why?” Block level indentation is the simplest thing for an IDE to take control over, and the actual act of block indentation is almost always hidden from the developer. It is also the easiest to reformat globally since the rules for that are relatively standard, configurable in most decent IDEs or, at the least, tolerable.

Even if this is the most tolerable solution, it introduces yet another wrench into enforcing style with other developers. Now you need to make sure a developer only uses tabs for block level indentation, and spaces for alignment purposes.


Spaces for tabs, two character indent

And here is the example that doesn’t include tabs at all, just spaces and a 2 tab indentation level. The benefit here is unmistakable intent.


There is no chance for confusion and what you see is what you get.

Contributors/teams do still need to set a common config as to the number of spaces for indentation, but that is better than assuming you don’t need to do that with tabs and getting conflicting code style regardless.

Personally, it really doesn’t matter to me as long as there is a standard. If you use tabs, then you still need to add the tab width you are coding with to coding guidelines. The reason I use spaces is because the environment is self-describing. If you see two spaces, you know the guideline is a two character indentation level. If you see a tab and effed up alignment, you need to experiment with a few configurations in order to find the style the original developers were coding towards.

(and yes, “flexible” or “smart” tabs sound awesome, but are impractical in mixed environments where IDE/editor support is so spotty)

if (someVar === otherVar) bar(); // If we're otherVar else if (isThing) otherFn(); // Do awesome stuff else quux(); // Do bad stuff!!

function bar() { if (anotherVariable === 42) { // If it's the answer anotherFunction(); } } }

if (someVar === otherVar) bar(); // If we're otherVar else if (isThing) otherFn(); // Do awesome stuff else quux(); // Do bad stuff!!

function bar() { if (anotherVariable === 42) { // If it's the answer anotherFunction(); } } }

if (someVar === otherVar) bar(); // If we're otherVar else if (isThing) otherFn(); // Do awesome stuff else quux(); // Do bad stuff!!

function bar() { if (anotherVariable === 42) { // Across block levels anotherFunction(); // it still breaks } } }

if (someVar === otherVar) bar(); // If we're otherVar else if (isThing) otherFn(); // Do awesome stuff else quux(); // Do bad stuff!!

function bar() { if (anotherVariable === 42) { // If it's the answer anotherFunction(); } } }

function updateExample(example,numTabs) { $('#'+example+' pre').html(TabFormatter.format($('#'+example+'Example').html(),numTabs,' ',1,'','')); }

(function(){ $('.tabExample button').click(function(evt){ var target = $(evt.target); var exampleId = target.parent().attr('id'); updateExample(exampleId,target.html()); }); updateExample('fourSpaceTab',4); updateExample('twoSpaceTab',2); updateExample('blockIndentOnly',2); $('#twoSpaces').html($('#twoSpaceExample').html()); })()

39 thoughts on “Why I use spaces over tabs”

  1. Jarrod- I also agree with what you’re saying. Another EXCELLENT benefit of using 2 spaces/tab is that when you want to share code (stackoverflow, gist.github.com, jsfiddle.com, etc…) and you copy from your IDE and paste in the “DHTML” enabled textareas, you actually get readable, code. Try cutting/pasting something that is tab based!

    Additionally, I think I saw an option the other day in git to auto-change all tabs to spaces (you specific how many). So no matter the mix or preference of your development team, what gets committed at the end of the day is the same. Kind of like a coding zen garden :-)

    1. @Brad Dougherty

      Putting comments on the end of the line is not “weird”. Nor is it the only case where people indent stuff *beyond* the initial indentation. It’s common these days to use a “column” view of variable assignments, for example.

      Forcing everyone to put comments on the previous line, however, *is* weird and limiting.

  2. Forcing anyone to use your point of view about what is nice or not, *is* weird and limiting.
    It’s just a matter of style, PREFERENCES in the deep. Even when you think there is some advantage using one method or other, really all is a problem of preferences.
    I used to use tabs, now i’m moving to using spaces instead tabs, and exactly 2 spaces… i was doing it before reaching this site, so…

  3. I’m glad to see all the points made against 4-column-tabs are irrelevant in the real world.

    Now one concern is really important however: how do we achieve consistency ?

    How about, since 4-col-tabs are really the most standard, let’s drop everything else ?

    Oh, and I have a whole blog post on the topic that really addresses all the points that can be made over tabs, spaces and other indentation.

    http://ludovicurbain.blogspot.be/2013/06/code-indentation.html

  4. Every IDE/editor has (at least it should!) tab->spaces and backward transformation. If you like spaces then use them. I will get your code, my editor will automatically transform your spaces to tabs and I will feel like home. Next you will do the same (but the other way around) and you will be happy.

    The biggest issue about spaces is when you – a 2-spaces fan – work with a 4-spaces fan. How will you work? If you used tabs there would be no problem AT ALL. You will see 2 spaces, he – 4 spaces and you both will be happy.

    And about comments at the end… There is NOTHING more annoying than that! It’s against readability. If you set your editor to not-wrapping mode then you need to scroll horizontally. On the other hand if you choose wrapping mode then there is nothing different in the look of your code and the code with comments one line before.

    I’m writing this based on my own near 10-year experience in coding with many different people, many languages and environments and on dozens of projects.

  5. Comment blocks like that are terrible idea. What if I need to change 1 line and other 3 expands automatically to be visually aligned? I changed 1 line, but version control shows 4 changed lines.

  6. If you ignore the side-aligned comments for a moment, then tabs come out of your demonstration pretty well, you can modify the tab size and the code looks good for everyone.

    I personally like the side-style comments, however, obviously, you can’t indent them with tabs because they fall apart with different tab widths. You need them to be the same size so that all the lines will always match up.

    It’s good that the indent sizes can be changed, but it’s bad that the comment gap sizes can be changed.

    Therefore, to me, the solution is clear: use tabs for indentation, and use spaces for alignment in situations where tabs will not work. It’s not inconsistency, it’s just *using the right tool for the job*.

    This has the advantage of not inflicting your tab width choices on other people, while also being able to produce aligned comments and code and stuff. The only problem is that some editors want to transmute your tabs to spaces or back again — which I feel is quite wrong, as they are not the same thing.

  7. The main reason to use tabs rather than spaces IMO: I don’t know about you guys, but I mostly navigate through the code using the arrow keys. It is so annoying when I find some code indented with spaces and I have to go through all these spaces to reach the word i want to edit!

    And seeing that the main reasoning for using spaces is the side-line comments (which I personally use and like as much as the above-line comments), here is the alternative: Let’s agree with all the team the width of the tab character so everyone can see the code well formatted.
    You’d have to reach an agreement anyways if using spaces regarding the amount of spaces to use, so why not use tabs and agree in the tab width configuration instead?

    I don’t really see the point of using spaces :)

  8. I think the most spaces vs tabs discussions are about indentation.
    Not about how you align comments & other stuff.

    There is no advantage on using spaces over tabs for indentation IMO.
    It’s annoying to navigate through spaces with the keyboard.
    It slows you down when you are trying to select text which starts the beginning of a line (You have to be more precise to NOT include the space).

  9. !)
    Almost all programs use now tab = 4 spaces as default;
    All programs allow to customize the tab length.

    2)
    Experience:
    Once, i had a very long PHP file. I replaced every 4 spaces with 1 TAB. After, the file was 50kb LIGHTER!
    The server with the repository had hundred of such files. A lot of Mb wasted.

    3)
    not possible to have problem like using 7 spaces instead of 8

    4)
    not need to agree how many tabs to use: tabs is always one, spaces are usually 4, but some prefer 2 spaces.

    5)
    it’s FASTER to tab than to 4-space

    6)
    In a file with TAB, one can know which character is used for indentation and which one for spacing.


    Compared to that, the problems mentioned in this article are irrelevant, and anyway very rare.

  10. Spaces are bad for indentation for much more common reasons than what you’ve listed here for Tabs.

    The number one complaint about spaces is that they’re more work to de-dent in most editors because you can’t effectively use the Backspace key. Go edit some code in JSFiddle and try de-denting your code by pressing Backspace. You have to press it four times to de-dent. If you used two-space indents, you’d have to hit it two times. Twice or four times the work.

    Also, many editors get de-denting wrong so you can’t even fall back to using Shift+Tab. Try de-denting *just* the word Hello in this code without using Backspace – http://jsfiddle.net/p74ve/

    It’s funny that it seems to be mostly web programmers who prefer spaces – which were not invented for indentation – as they shoe-horn HTML and HTTP into any and every possible role.

  11. Space vs tab, a different opinion. Why I prefer tab (or: why tab exist):
    1)
    Almost all programs use now tab = 4 spaces as default;
    All programs allow to customize the tab length.

    2)
    Saved space:
    Once, i had a very long PHP file. I replaced every 4 spaces with 1 TAB. After, the file was 50kb LIGHTER!
    The server with the repository had hundred of such files. A lot of space wasted with no gain.

    4)
    not need to agree how many tabs to use: tabs is always 1, spaces are usually 4, but some prefer 2 spaces.

    6)
    In a file with TAB, one can know which character is used for indentation and which one for “string spacing”.

    3)
    no problems because somebody used 15 spaces instead of 16

    5)
    it’s faster to type a tab than to 4 spaces

    7)
    the allignment is easier to obtain, the comments are nicer to see with less effort

    Conclusions
    – Of course, that’s only my opinion and anybody can have a different one.
    – I think that (2) is the one that in practice has more importance, and generally most of them are part of the reasons why TAB exists.

    1. Re. “2: Saved space on disk”
      This is IMO no longer relevant. We’re in the age of terabyte disks. Also with compressing proxies (Opera and Google) and also on-the-fly gzip compression done by the server and undone by the client, over-the-wire space isn’t that important either – especially, if one takes into consideration, how many images and how huge these beasts are.

      No, space is no matter. That’s not the 90ies anymore.

      1. Maybe it’s not very relevant… but you don’t gain anything by using more space and generating more C02.
        And here another one:
        8) when you move some code from an inner block to an outer one, it’s easier to remove 1 TAB for each line than 4 (or X) spaces. Example:

        if(condition)
        {
        boolean condition = true //this code must be moved before the if(1)
        ….

        }

        // (PS i saved this code with spaces but they are removed by disquss)

      2. No, space is very much a relevant matter, thanks. In one handover job earlier this year, we were doing a database backup over a slow connection, and the 10 GBs dump took forever to download. When I checked the tables to find which were the ones had caused the most bloat, I found a 5000+ long log of HTML newsletters that’d been sent over the years. One of the columns logged the template code, which – surprise, surprise, had been indented using spaces.

        Granted, this is an edge case and the dump still would’ve been huge, but had the coder have used tabs for indentation, the damn log wouldn’t have taken forever to transfer when we already had our hands full.

        Furthermore, people who argue that Gzip compression eliminates all latency concerns with space-delimited code probably forget that their bandwidth could *still* be optimised even further by sticking to tabs for indentation instead of spaces. And, hey, sure you could argue that in an age of hyper-fast broadband that’s no longer relevant either, but remember mobile users – and even with 120-bytes of useless junk shaved off every plain-text file transferred, it has a pretty big impact in the long-term.

        *TL;DR:* Use .editorconfig to set your formatting preferences and give the whole “it looks different to other coders” crap a rest.

    2. > All programs (or almost) show tab = 4 spaces as default

      Not all programs default at 4 tabs. IDEs for Ruby default to 2 spaces, for example.

      > All programs (or almost) allow to customize the tab length.

      This is true, but this assumes that you *know* what the intent of the coder was. I will have to keep playing with tab sizes until it finally looks right. However, different developers have different settings, and their code reflects that. In the case of open-source software, for example, you end up with code contributions of differing whitespace alignment, which I’ve seen over and over again.

      1. Then I suggest you use .editorconfig files so these nuisances can someday be made history. The beauty of these files is that they outline the coder’s intent in plain-writing, and IDEs can be configured to set project-specific whitespace settings from its .editorconfig manifest.

  12. Tabs are clearly superior to spaces :-)

    Take the scenario where you’re using spaces.
    You want to indent a line? You press TAB and the editor gives you X spaces.
    You decide you didn’t want to indent that line? Press Backspace. Instead of removing the indentation, you now have an indentation of X-1 spaces.

    I rest my case…

    1. Any decent editor is either smart enough to figure that out on its own and remove the entire indentation worth of spaces, or configurable enough that you can make it behave that way. Worst case, use shift+tab.

      1. Lewis: you’re implying every editor will have that configuration. If I have to patch something in Notepad in a VMWare environment, I’m going to be using the tab key to indent code. Period.

        1. You can’t possibly be serious. If you’re going to be editing code in Notepad so frequently that this matters (i.e. at all, ever), you would immediately benefit from making some easy changes to your environment.

          Notepad is quite literally the only editor anyone would ever use ever that doesn’t support using spaces for indentation – even nano can do it – so yes, I am indeed implying that every editor that matters will have that configuration. It’s ridiculous to bring up Notepad while you’re going around telling everyone to just use .editorconfig, which some editors don’t support at all (and almost all editors that do need a plugin).

          Playing nicely with a bad editor that can’t even get line breaks right is simply not on the list of things I’m worried about. If you’re editing code inside a VM and not being obtuse about it, then you should have some way to get those changes into your source control. This means either having a development environment in the VM (and thus not needing Notepad) or having a volume mounted to your host machine (and thus not needing Notepad).

          1. Slight error in communication here. I wasn’t implying one would *want* to code in Notepad, simply that sometimes, coders won’t always have a choice in what program they have to use.

            Going back to my original hypothetic example, in the off-chance that I AM making a stupid fix to crap code in a restrictive environment, I’m not going to copy+paste diarrhetic runs of space characters just to appease some a spaced-out coder, or mindlessly tapping the spacebar like a confused old person. I’m going to be hitting the tab key, which I can do so in a proper editor, too.

            (I’ll admit this is an edge case that’s kinda tangential to the main discussion).

          2. Yes, I understand your hypothetical, and of course nobody would *want* to code in Notepad – I just don’t buy the notion that anyone is ever actually stuck with Notepad for actually editing actual code.

            There’s a sort of similar argument that we need to support old web browsers because enterprise IT departments are five years behind, and thus people are stuck with IE8 at work. I buy that, and there are numbers to back it up, but being five years behind on your browser is completely different from being 20+ years behind on your editor. Any developer with enough freedom to do his/her job also has enough freedom to use something (literally anything) other than Notepad.

  13. Your examples to justify spaces are flawed IMO.
    You shouldn’t use alignment of comments this way in the first place – simply for the reason that this creates a lot of additional noise in change diffs (Github PR diffs for example). And that is independent from whether spaces or tabs are used.
    Imagine one line becoming longer, all other lines (above and below) would also need adjustment of the comment indentation. That’s just stupid.

    You should be using
    a) Tabs
    b) Never indent your comments (neither with spaces nor with tabs).

    $someVar = ‘foo’; // Some comment
    $someOtherVar = ‘bar’; // Some other comment

    Directly after the code a comment follows separated by a single space.

    Clean, easy, minimal noise, future proof and the right way to do it.

    1. ^ This. All of my this.

      Unless I’m writing YAML, Markdown, or text intended to be read in a terminal, I always indent my code with leading hard tabs. Because, yeah, that’s kinda why tabs were invented… to indent text into columns.

  14. Hah. Why not. I’ll bite and join in the holy war.

    I really dislike indentation using spaces since I’ve yet to see an editor that will replace 4 spaces with 2. You put a line of code in an if statement in a for loop in a method in a class? Seems a reasonable level of complexity, until you realize it’s a quarter of the way across the screen. Kind of joking, but I find having that much white space in a file very distracting.

    On the flip side of “tying other to your style descision” is that by using spaces, you are tying others to how much white space looks “normal” to you. Tabs are the magical solution that makes it possible for everybody to be happy.

    My opinion on carefully aligned comments is just don’t do it. If you are like me, every job or open source project you look at seems to have an annoying mix of tabs and spaces that will make them always wrong all the time anyway. Until compilers decide that one or the other is a compile error anyway…

  15. I don’t get this discussions about tabs over spaces. We have stupid but fast computers and clever but slow people. So why is anybody doing stuff that can be done by computer? Like indenting the code. I think that it is waste of time and money and even more money to manually format code. Just specify some formating rules and use them!

  16. I have to agree that the alignment you use for the comments and the contents of the if/else blocks just slows down my reading of the code. I suggest that our minds are adaptable enough to work just as efficiently without that level of formatting. Vertical separation does far more to distinguish which parts of the code are related. We tend to read less efficiently when thoughts are spread across a greater horizontal distance.

  17. I’ve reading tabs vs spaces arguments for years and always stick with the tabs team. But I’ve never seen an good explanation on the “leads to confusion” argument. Congratulations, I’m going to be an space dude for now on. Hallelujah brother!

    WOLOLO

      1. You may think it’s incredibly convoluted, but I’ve seen WAY too many files with that exact problem: one developer had used 4-space tabs while writing the file, another had used 2-space (or 8-space) tabs, and now there’s no way to line up the comments they intended to be lined up.

        I agree with the tab advocates that tabs are clearly superior, in theory. But in practice, people use them wrong. It’s impossible to get spaces wrong, hence my STRONG preference for spaces: because I’ve seen too many developers screw up their files using tabs. The larger file size problem with spaces comes a distant second compared to the “Yikes, this file looks ugly as sin” effect that I get when I open one of those files where multiple people have edited it incorrectly with varying tab settings.

        1. So the issue is simply a matter of people not using spaces for *alignment* and tabs for *indentation*.

          Quite simply, if you’re using tabs to neatly align anything for aesthetic purposes, you’re inviting doom.

          Solution: if your IDE doesn’t allow “smart tabbing” (switching to spaces when inserting an indent after a non-whitespace character), just avoid aligning with tabs altogether (or just save your effort for manually aligning more pertinent things like comment blocks).

          It’s funny that you mention the “ugly as sin” part, because that’s exactly what I think whenever I read any 2-space indented JavaScript these days. Seriously.

Leave a Reply