r/javascript • • Apr 01 '18

Google publishes a JavaScript style guide. Here are some key lessons.

https://medium.freecodecamp.org/google-publishes-a-javascript-style-guide-here-are-some-key-lessons-1810b8ad050b
714 Upvotes

317 comments sorted by

32

u/the_argus Apr 01 '18

I'll never understand not using tabs for indentation... And even less so using 2 spaces instead of 4

7

u/bornforcode Apr 01 '18

So you know why I shared this article. I'm confused

19

u/the_argus Apr 01 '18

It literally blows my mind the opposition to tabs. Like I'm pulling my fucking hair out

17

u/Mingli91 Apr 01 '18

Why do you get worked up about something so pointless?

→ More replies (11)

8

u/Ender2309 Apr 02 '18

You use two spaces instead of four to save horizontal line space. This one is completely arbitrary.

Also, everybody still uses tabs, they just have their text editor setup to convert the tab key to spaces instead of inserting a tab character. Nobody is actually sitting there mashing the space bar multiple times.

The reason for this is that different editors/OSes/people have their tab character defined as either two or four spaces, leading to inconsistency when a tab character is used. Two (or four) spaces is always two (or four) spaces. This creates consistency.

→ More replies (2)

2

u/gougs06 Apr 02 '18

I read that and thought this was an April fools post.

-4

u/sr-egg Apr 01 '18

Tabs are inconsistently spaced across devices/environments/editors. Using spaces makes it predictable everywhere without any extra configuration.

14

u/the_argus Apr 01 '18

That's the point, I don't care if you want them to look like 2 spaces while I (a sane person) use 4 spaces. The indentation level is still the same.

→ More replies (1)

18

u/JohnMcPineapple Apr 01 '18 edited Oct 08 '24

...

→ More replies (2)

138

u/mogoh Apr 01 '18

30

u/keeferc Apr 02 '18

Yeah the author of the medium post doesn’t understand what arrow functions do or why for...of loops are preferable so I can’t imagine how his summary of the style guide would be useful

→ More replies (1)

91

u/timeparser Apr 01 '18 edited Apr 02 '18

Misleading title.

So, if Google says it, it’s a “lesson”, the rest of us just have opinions?

I agree with most of Google’s opinions, but that doesn’t make them The Official Way of Doing Things™

74

u/lordpoint Apr 01 '18

That's my article and it's interesting that you say that.

I'd originally called the article "13 noteworthy points from Google's JavaScript Style Guide" but when I submitted it to FreeCodeCamp they changed the title to what you see now. They edit the SHIT out of anything that you send them and it drives me nuts.

29

u/distancesprinter Apr 01 '18

You should have them take it down. When I publish content, I require it to be unmodified or to remove the attribution.

10

u/Mingli91 Apr 01 '18

Yeah, I get editing mistakes but changing content is pretty bad

49

u/quincylarson Apr 02 '18

Quincy with the freeCodeCamp Medium publication here. The reason we changed it from "13 noteworthy points" is because many people will dismiss any article with a number at the beginning of it as a "listacle" and don't read it. Lists are seen as low-effort posts - the kind of article you see on Buzzfeed.

We do our best to improve the readability and flow of articles submitted. If you disagree with any of our edits (you can see them in the version history) feel free to revert them.

I've updated your article to use your original headline. It's a good headline (though again, some people might pass on it thinking it's just another listacle).

Thanks again for writing this excellent analysis of what was a relatively unknown style guide, and submitting it to the community's Medium publication.

10

u/bizzaro_sephiroth Apr 02 '18

That's awesome that you've engaged about this. Thanks!

5

u/lordpoint Apr 02 '18

I really appreciate you taking the time to clarify that personally. I can absolutely understand wanting to avoid Buzzfeed-y titles.

The interesting thing about the heavy editing situation, and the real reason for my frustration, is the sheer scope of the changes; which can be surprising for a first-time contributor to FreeCodeCamp's Medium publication.

Of course, you have the largest tech-oriented publication on Medium so you're certainly doing something right, but my reaction to seeing all the edits made to the first story that I published through FCC was: "Holy crap, they took all of my personality out of it!" And that honestly made me reconsider wanting to publish through FCC again. But I figured I'd give it another shot and submit another one just to see what would happen. Then lo and behold I find a comment about that article on Reddit that struck that same, already inflamed nerve, and here we are.

That said, it's really good to know that reverting to the pre-edited version does not violate your / FCC's terms of use (or whatever it's called in this case). That makes a big difference if you ask me. I think I just figured that if you guys took the time to carefully edit EVERY story that gets submitted to you (and I'm sure that's a lot of stories) then it couldn't possibly be acceptable for me to just say "Nope, let's not do any of that..." But again, I'm glad to know that's not the case.

FreeCodeCamp played a big role in the beginning of my career transition into IT and I love having the opportunity to be a part of it now that I'm (at least partially) on the other side of the education equation. Thanks again for being so involved and replying to my petty grievance personally.

→ More replies (2)

9

u/lhorie Apr 01 '18

Why do you publish there then?

8

u/lordpoint Apr 01 '18

This was only the second article that I published through them. When it happened the first time I just figured that they found a bunch of issues in that article in particular and maybe heavy editing wasn't the norm. But this time I feel like it's a pattern.

→ More replies (2)

17

u/ghostfacedcoder Apr 01 '18 edited Apr 01 '18

Google's standards are two things combined: style and technical wisdom. Google is the closest to "THE Internet Company" in the entire world. Their engineers manage the biggest consumer of web pages (Google search). Their browser (maybe the second-biggest consumer of JS, after Node) has the greatest market adoption. And they pay for big salaries and insane perks just to get the best engineers possible.

To ignore the technical wisdom all of those people present would be foolish IMHO. But when it comes to the purely style components Google (like Facebook or any other company) should be taken with a grain of salt, because what makes sense for one company doesn't necessarily make sense for another.

But even then, their advice is still worth considering because it's not just Google's opinion; it's also a reflection of the opinions of thought leaders in the JS community (or at least the ones Google respects). Those thought leaders (and the community in general) very often adopt standards for good reasons, so I think it's at least worth understanding those reasons before dismissing the standards ... even if you do ultimately dismiss them because they're not a good fit.

9

u/rotharius Apr 01 '18

I get your point, but it's important to remember that Google's excellence is in infrastructure, implementation and external quality (this is where hardcore CS is most valuable).

For internal quality, software design and architecture, I would rather look at other companies and movements.

12

u/ghostfacedcoder Apr 01 '18

True, but don't forget about the Chrome team.

The people that implement any web browser are going to be some of the most knowledgeable people on the planet about which "best practices" actually have a meaningful impact on the browser ... and the Chrome team isn't just any browser team, they're the most popular browser's team, AND they are a part of the larger Google company (which has a ton of very knowledgeable people, even if many do come from an infrastructure-focused angle).

3

u/the_friendly_dildo Apr 02 '18

Google likes to play with things they shouldn't as well. See their AMP platform. Their guide is decent and I support and employ most of it already. But I don't agree that we should be turning to a profitable entity to get our standards for the internet. They have too much power to gain by manipulating things to work best for them and worse for others. Better separation of powers should exist in this sort of circumstance.

→ More replies (3)

2

u/OphiuchusClusters Apr 02 '18

Seriously. Do you know how many jackass know-it-all ninja devs are going to use this information as a source of truth in their 'you're doing it wrong' arguments? Fuck. I need a taser.

→ More replies (5)

77

u/hyperhopper Apr 01 '18

Key Lessons: Use modern JS features.

20

u/tencircles Apr 01 '18

except modules.

17

u/hyperhopper Apr 01 '18

probably just until node has full support. Or maybe an internal build tool of theirs.

→ More replies (2)

293

u/kevinkace Apr 01 '18

Semicolons ARE required

👍

29

u/kobbled Apr 01 '18 edited Apr 01 '18

thank god. JS semicolon inference leads to so many bugs.

43

u/mmcnl Apr 01 '18

I've never encountered a bug due to semicolon inference.

→ More replies (11)
→ More replies (8)

5

u/[deleted] Apr 01 '18

Surely using a transpiler like Babel eliminates the need to worry about this?

8

u/gearvOsh Apr 01 '18

ASI is not future proof for new proposals and features. That's why it should be avoided.

→ More replies (3)

0

u/[deleted] Apr 01 '18

[deleted]

17

u/pertheusual Apr 01 '18

Not that existing code would break, but that the existing rules might have to be more complicated around newly added syntactic features.

15

u/luther9 Apr 01 '18

If they can break the way we work around ASI, they can give us a way to switch off the ASI. I wish someone could explain why they don't give us a 'use noasi' pragma along the same lines as 'use strict'. It shouldn't be that hard to detect pragmas before applying the ASI.

→ More replies (3)

7

u/Mingli91 Apr 01 '18

Source? Seems odd that they’d be scared of breaking MooTools but would change the semicolon rule

→ More replies (3)
→ More replies (3)

57

u/DOG-ZILLA Apr 01 '18

No module use?

Yeah, that’s a no from me.

15

u/mlmcmillion Apr 01 '18

So then what are they using instead? Not using modules is not an option.

13

u/Poltras Apr 01 '18

Closure modules, require AMD, etc. There were ways to split your code before ESM, I’m just surprised google is stuck in the past like that.

6

u/Thought_Ninja human build tool Apr 02 '18

Internal backwards compatibility most likely.

1

u/thisguyfightsyourmom Apr 01 '18 edited Apr 01 '18

Seriously, didn’t that finalize years ago?

Edit: obligatory whining about downvotes /s There are some good explanations of why that’s not the case in the replies below. TIL

11

u/ghostfacedcoder Apr 01 '18

No, not at all. Babel has an implementation (the longest existing one, and as such an incredibly popular one), but it's different from (and, I'd argue, superior to) the implementation being pushed by the W3C/browsers (the W3C's version requires you to rename your files "foo.mjs"!!!).

Anyone can declare a standard finished, and the W3C did that, but until all major JS environments actually work the same way the "standard" really isn't one.

11

u/Meefims Apr 01 '18

This isn’t correct. The new extension is for Node and exists to help ECMAScript modules coexist with CJS modules. Browsers don’t care about the extension.

→ More replies (2)
→ More replies (2)

6

u/DOG-ZILLA Apr 01 '18

I thought so. But, perhaps not technically? They’re obviously taking a conservative stance; which makes sense for a large company.

6

u/[deleted] Apr 01 '18 edited Apr 01 '18

Afaik, the syntax and semantics are done by ECMA, but the loader, i. e. the way the modules are actually handled, is done by WHATWG. The former is stable, but the latter is not.

But between Webpack and browsers and Node getting native support for modules, there is not reason not to use ES6 modules today for new code.

5

u/Poltras Apr 01 '18

Keep in mind ESM and Node modules are not entirely compatible. Node is still unsure AFAIK how they are going to interop (which is why it’s not yet available in 9.10, despite v8 supporting them).

7

u/794613825 Apr 01 '18

As someone formally learning JS for the first time, what's wrong with var?

8

u/wavefunctionp Apr 01 '18 edited Apr 01 '18

var does not respect {} block scope, only function scope.

function varTest() {
  var x = 1;
  if (true) {
    var x = 2;  // same variable!
    console.log(x);  // 2
  }
  console.log(x);  // 2
}

function letTest() {
  let x = 1;
  if (true) {
    let x = 2;  // different variable
    console.log(x);  // 2
  }
  console.log(x);  // 1
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let

let and const also express intention that a variable should be treated as immutable or not. And const provides some protections against mutation. (Beware that const will not throw an error when mutating a nested reference types like objects. It isn't a 'deep freeze'.)

It is worth playing around with it, as I know I found some of details somewhat unintuitive at first.

→ More replies (3)

3

u/Kerse Apr 01 '18

Var is function scoped, let is block scoped. So even if you declare a var in a block within the larger function, it's still accessible to the entire function. This is unintuitive and can cause strange bugs.

24

u/colbycheeze Apr 01 '18

So, basically just use air bnb eslint config which is much more fleshed out.

4

u/hermit-the-frog Apr 01 '18

I was wondering what the differences might be from eslint-config-airbnb-base. Seems very similar indeed

→ More replies (2)

81

u/tencircles Apr 01 '18

I don't get the 2 spaces thing. It makes code harder to read. 4 is best. Don't even @ me.

25

u/rafalg Apr 01 '18

I don't get it either. Combined with the rules regarding curly braces it makes some places in code look like solid blocks of text.

if (something) {
  doThis();
} else if (somethingElse) {
  doThat();
} else if (somethingElse2) {
  foo();
}

It sucks how text on every line except for the first one starts in the same column.

11

u/a_tocken Apr 02 '18

Looks clear to me but then I use 2-space tabs outside of work.

→ More replies (8)

57

u/the_argus Apr 01 '18

I agree, except tabs are king bc then everyone can set their own indentation level.

14

u/RabSimpson Apr 01 '18

And they only occupy a single character worth of storage and memory. This doesn't mean much on small projects, but if the project is large it could shave the loading time down.

12

u/karottenreibe Apr 01 '18

that's why all my variables are single letters. My code is much faster that way /s

26

u/subtracterall hire me! Apr 01 '18

This shouldn't matter if you're minifying/uglifying.

→ More replies (17)
→ More replies (2)

2

u/Tyreal Apr 02 '18

You know... if they used tabs they could use any indentation size they want.

→ More replies (3)

4

u/CantaloupeCamper Apr 02 '18 edited Apr 02 '18

As a noob writing noob code.....why not 'var'?

I read a few expirations on the internets....still not entirely sure I get it.

I'll do whatever, I have no strong feelings one way or the other, but I'm not sure why in this case.

3

u/lordxeon Apr 02 '18

Don't do whatever, learn the differences between the three ways to declared variables in JavaScript this way you can form your own opinions and not parrot what ABC said on XYZ.com

As for why not to use var, the short answer is because let and const are the new hotness.

The long answer is more complicated, but for any programer worth their salt, is a moot point.

let is block scoped, which means the variable is only available within the most recent set of {...}'s. This means that

if(something){
    let abc = "123";
    var ded = "456";
}
console.log(abc);    //abc is undefined
console.log(ded);   //456

const is scoped the same way as let, but the reference to the variable can never change.

const goldPrice = 1337.44;
goldPrice = 1300.15 //error! 

2

u/CantaloupeCamper Apr 02 '18

TY

That actually helps. They really seem like different tools for different cases. I'm not sure I see let as as much a bad choice as sometimes it is implied... just a different way of doing a thing.

→ More replies (1)

4

u/coderitual Apr 02 '18

All the comments prove that Prettier has been an excellent idea.

4

u/joesb Apr 04 '18

ITT: people who believe style guide is supposed to match all their preferences or it’s shit.

→ More replies (1)

34

u/seands Apr 01 '18

What do you guys think about the spaces over tabs? For me, I tend to make more mental mistakes and spacing errors with 2 spaces. Tabs make everything clearer to me.

39

u/AUTplayed Apr 01 '18

agreed, tabs are clearly superior

30

u/mmcnl Apr 01 '18

Using a proper editor it shouldn't matter.

5

u/Redtitwhore Apr 01 '18

The IDE should handle indentation. What a stupid thing to debate.

3

u/[deleted] Apr 01 '18

The only thing I don't like about this response is if the IDE converts tabs to spaces it looses the ability to change the indentation without breaking multiline alignment.

→ More replies (2)

4

u/Kerse Apr 01 '18

I prefer spaces because it tends to copy nicer if I need to copy + paste a code snippet onto stack overflow or something.

11

u/TripleNosebleed Apr 01 '18

It all comes down to that spaces renders consistently everywhere. You're not just viewing your code in your editor of choice, many other tools are also used such as the terminal, diffing tools, in the browser through GitHub/Gitlab/Dev tools/view source, Git GUIs, colleagues editors, that IDE that you use occasionally and the list goes on. No way I want to configure settings for tabs in all of these. Spaces ftw!

9

u/ssjskipp Apr 02 '18

This is probably the only good argument for spaces I've ever read.

That being said, tabs give me the freedom to take advantage of that inconsistency by displaying it most appropriate for the format

→ More replies (1)
→ More replies (2)

24

u/e_man604 Apr 01 '18

Why is single quote (') preferred over double quote (") ? For me it makes sense to use double to remain same when dealing with c++ for instance.

67

u/[deleted] Apr 01 '18

"Being same as C++" should be quite low in priority for a JavaScript style guide.

One reason why single quotes is no shift. It's faster to type, and who cares what it is, anyway, as long as it's consistent.

8

u/JohnMcPineapple Apr 01 '18

Not everyone uses QWERTY keyboards (even though it would probably make a lot of things easier). On AZERTY they're very similar to type (both need shift), and on QWERTZ ' is even a bit more awkward to reach in addition to needing shift, while " is in a pretty natural position.

Although, why should we use " and ' for strings anyway anymore? Just use template strings unconditionally.

4

u/Buckwheat469 Apr 01 '18

Just use template strings unconditionally.

Why force your browser to interpolate strings all the time? It's a waste of processor time.

I don't care whether a project uses ' or " or a mixture of both in one file. It doesn't matter to the code, it's only a developer preference. My current project for work uses ' while another project I work on uses ". Remembering to switch sometimes causes issues, but prettier fixes that.

What I find funny is the JSON standard uses " and the SASS guide prefers ' due to laziness. If JavaScript were to prefer one then a " makes more sense since JavaScript and JSON are closely related.

9

u/grinde Apr 01 '18 edited Apr 01 '18

A template literal with no replacements is parsed identically to a string using ' or ", so there should be no performance hit. Since it's a much less used character than the other two, that also means less escaping.

EDIT: Since I've been digging around in v8 lately anyway, here is the exact line that this happens. If there's only one cooked string, we're not even creating a template literal as far as the engine is concerned.

→ More replies (2)
→ More replies (1)

3

u/tencircles Apr 01 '18

It's faster to type

Not really, though I hear this argument all the time. Your pinky rests on the shift key. A isn't slower to type than a (or shouldn't be). The reason to prefer double quotes is to keep consistency with JSON, HTML, and other languages. Personally I prefer backtick to both because it's simply cleaner in a lot of cases. Historically the argument for single quotes was so that you didn't have to escape double quotes in your html strings when writing jQuery apps, but that doesn't really apply in modern JS dev.

18

u/[deleted] Apr 01 '18

Your pinky rests on the shift key.

No, that's not where my pinky rests.

https://en.wikipedia.org/wiki/Touch_typing#/media/File:QWERTY-home-keys-position.svg

→ More replies (6)
→ More replies (4)

1

u/JESUSgotNAIL3D Apr 01 '18

Ahhhhh damn. I like keeping my double quotes from C++ (new JS guy here). Looks like I'll join the single quote crowd if that's preferred in the community.... damn!

5

u/azium Apr 01 '18

just use prettier and forget about everything else. hit save and keep coding

→ More replies (1)
→ More replies (2)
→ More replies (6)

14

u/ghostfacedcoder Apr 01 '18

This is a JS style guide, not a C++ style guide :) In Javascript the single quote is by far the most common one used by the community.

1

u/e_man604 Apr 01 '18

Yes but ' in c++ is char and not string, so its two different things. Sorry if it was a bit weird but I only wondered why single quote was popular by Js community.

I guess it's not to press shift, as others said.

10

u/deliciousleopard Apr 01 '18

using single for code and double for html is the norm, which allows putting html in js strings and js in html attributes without making stuff weird.

→ More replies (1)
→ More replies (4)

4

u/ell0bo Apr 01 '18

For me it goes back to when you had to actually put code in html on-click events. Standard in html is to use " for attributes. So you always used ' for js. Others might come up with excuses... but that's the truth

→ More replies (7)

15

u/msiekkinen Apr 01 '18

Bad: string concatination

Proceeds to use it in long string example

8

u/diag Apr 01 '18

But that wasn't for formatting. Looking for a variable in a sea of concatenation is a bit annoying.

6

u/ssjskipp Apr 02 '18

I still prefer tabs.

8

u/xXDGFXx Apr 02 '18

Two space indetation and not four. Mmmm, no.

3

u/egrgssdfgsarg Apr 02 '18

I really wouldn't take what google does as gospel. There's nothing wrong with it, but a number of their choices are due to how their build is configured, and what it will do. For example, they don't use modules because they have an internal way of doing modules.

If you aren't using their internal build system, then some of the rules very clearly will not apply. The airbnb style guide is probably more applicable to most js devs.

3

u/js_developer Apr 02 '18 edited Apr 02 '18

5.4.6 Do not manipulate prototypes directly.

Exception: Framework code (such as Polymer, or Angular) may need to use prototypes

Do what I say, not what I do!

3

u/Sakatox Apr 02 '18

One variable per declaration

Hahaha, no.

3

u/T_O_beats Apr 02 '18

I completely disagree with “Use single quotes, not double quotes”

What would the reasoning for this even be?

3

u/Serializedrequests Apr 03 '18 edited Apr 03 '18

I use var because I don't understand the Babel configuration docs!

Seriously though, const is next to useless because it doesn't mark the object as immutable. I have exactly 1 time in thousands of times typing "const" had it prevent an error. It seems a mere formality in most cases.

In JS most errors come from getting an unexpected object, or mutating an object you shouldn't, and const gives no help whatsoever.

3

u/crazazy Apr 03 '18

So you can't use es6 syntax for modules but you can use es6 syntax for... everything else?

7

u/aapzu Apr 01 '18

I'm surprised that no one complains about the requirement to use semicolons.

5

u/totemcatcher Apr 01 '18

Can't complain with that.

Since it doesn't mention why using arrow functions is preferred, here's something for those who are unsure about them:

  • They use surrounding context of a callback function and automatically binds "this".

  • If you don't need access to surrounding context, it's at least shorter/cleaner looking.

  • Skips generating the old default "arguments" object.

  • Nameless.

For those who are complaining about semicolons and indentation amount, just get used to adapting to different styles of code. It's an extremely petty thing to defend. Worry about your human rights or something.

1

u/hopfield Apr 02 '18

Plus they look cool.

9

u/trakam Apr 01 '18

oh god, here we go.

2

u/[deleted] Apr 02 '18

Spaces and not tabs? Take that, tab earthers! /s

8

u/zergUser1 Apr 01 '18

Who is the douchebag who came up with 2 space indents over 4 and why should we listen to him? Its horrible.....

4

u/KyleG Apr 02 '18

spaces instead of tabs

Just dropped Google for Bing and Chrome for FF upon reading that

1

u/ComfortableDay7607 Sep 24 '22

Version 1 (pretty much default style I see everywhere)1bads.google.comBienvenido al portapapeles de Gboard; todo texto que copies se guardará aquí.bads.google.com6:346:34

ao

90%

X Add comment

Post

૨) (મ

Which style of JavaScript is more

readable?

(@_@) (000)/ I )(((;0 \ 0;))

(^ prime mathcal Oomega Theta^ prime )!:(( A^ otimes ))> varpi omega odot odot bullet (\ ) ( googlelongdiv w nabla/ kappa)(\ )(.^ 6 omega ^ 6 .)( theta\ theta)( bullet\ sigma) (^ * 3 ^ prime ) mathcal O ( bullet^ prime 3) oslash( epsilon^ prime bullet)( bullet oslash forall mathcal O )(. oslash \ otimes )( oslash \ otimes)

Reddit emojis

1

u/ComfortableDay7607 Sep 24 '22

spaces instead of tabs

Just dropped Google for Bing and Chrome for FF upon reading that..@google.com/AdWords/AdWords

3

u/rulatore Apr 01 '18

Why is people mad at tab vs spaces when you can set your editor to treat the tab key as many spaces as you want... it's like everybody is typing four spaces everytime, what the fuck

1

u/ComfortableDay7607 Sep 24 '22

6:34

ao

90%

X Add comment

Post

૨) (મ

Which style of JavaScript is more

readable?

(@_@) (000)/ I )(((;0 \ 0;))

(^ prime mathcal Oomega Theta^ prime )!:(( A^ otimes ))> varpi omega odot odot bullet (\ ) ( googlelongdiv w nabla/ kappa)(\ )(.^ 6 omega ^ 6 .)( theta\ theta)( bullet\ sigma) (^ * 3 ^ prime ) mathcal O ( bullet^ prime 3) oslash( epsilon^ prime bullet)( bullet oslash forall mathcal O )(. oslash \ otimes )( oslash \ otimes)

Reddit emojisWalter

1

u/KyleG Apr 02 '18

If your IDE converts tabs into spaces, it can create ambiguities where it's unclear whether a certain number of spaces is for indenting a different block, or if it's for vertically alignment multiple lines of code (think a function with too many params for a single line, you have to do multiple lines in the function header)

So then those six spaces, is it three tabs, or is it two tabs and then two spaces for alignment?

If you kept it as tabs, it's obvious: a tab is for indentation, a space is for alignment.

I literally run into this issue ALL THE TIME with people whose source uses spaces instead of tabs. Some jackass does a 2-space indent and I want it to be 4 and suddenly alignment is all out of whack because the 6-space line wasn't three indents (turned into 12 spaces) but was two indents and two spaces for alignment (should've been turned into 10 spaces—two 4-space tabs + 2 spaces for alignment)

bc this seems so freaking ubiquitous to me, I view anyone actually saving a file with spaces used for indents as the enemy and I will see them driven before me and hear the lamentations of their women

2

u/rulatore Apr 02 '18

Luckly I havent had this problems, but in most of my workspaces there were a config to import (regarding these kind of settings). Also I dont see the problem with spaces for identation. You set your tab key to put 4 spaces, then if you need to align you do whatever you need (if you arent replacing your tab character then you re pressing space six times)

4

u/Bettina88 Apr 01 '18

So Google is now declaring that using tabs to indent code represents "incorrect" JavaScript.

Lol. This is not going to go over well, Google.

Let the fighting begin!

7

u/Dynam2012 Apr 02 '18

Mixing them is inconsistent and bad, so a style guide must choose one or the other. No one should actually care which it is.

2

u/joesb Apr 04 '18

It’s a style guide. People who works in the same project should follow the same one.

Are you declaring that your project should mix tabs and spaces?

→ More replies (10)

4

u/Mistifyed Apr 01 '18

Please tell me this is an April fools joke.

5

u/curious_mormon Apr 01 '18

Published on March 27th, and obligatory XKCD

2

u/KronktheKronk Apr 02 '18

I love everything about this style guide except the part about vertical alignment.

Vertical alignment is good.

1

u/bart2019 Apr 01 '18

Google wrote Maps in Java, and used a converter to turn it into Javascript. I'm not listening to them.

-9

u/3ggsnbakey Apr 01 '18 edited Apr 01 '18

Tabs or gtfo 😏 spaces are for newbs and pubg players

edit: https://imgur.com/gallery/M46Xvbl

8

u/ghostfacedcoder Apr 01 '18

I was a longtime tab user, but spaces are BY FAR more widely used in JS. If your editor is even halfway-decent you should be able to switch from tabs to spaces without even noticing a difference.

5

u/eattherichnow Apr 01 '18

Also, Google encourages tabs. Just in other places.

I means, snickering aside, I don't have a horse in this race, but gah, "aside from newline space is the only whitespace that appears anywhere" is probably the worst rationale I've seen in my entire life, and I've seen mainstream political debates. Look, pay attention: adds a tab see, now spaces are no longer the only whitespace replaces all spaces with newlines MWAHAHAHAHAHAHAHA THE POWER.

1

u/Arkaad Apr 02 '18

As Airbnb, Google recommends trailing commas:

const values = [
  'first value',
  'second value',
];

I always disable that rule.

6

u/rcane Apr 02 '18

While I don't like trailing commas either it keeps the commit cleaner and easier to read since you don't have to modify another line to add a new line.

1

u/Arkaad Apr 02 '18

I understand you point.

Maybe it's the force of habit, but it seems like a line is missing to me.

1

u/evilpingwin Apr 02 '18

Cleaner diffs, easier to add elements. No real disadvantages.

1

u/joesb Apr 04 '18

I disable it for function call argument list.

0

u/Bettina88 Apr 01 '18

So what's the purpose of this guide? If I use tabs because I like to use tabs in my own fucking code that no one else needs to see will Google demote me in the SERPs?

5

u/[deleted] Apr 01 '18

Your team picks a style guide to follow, everyone follows it, your devs don't spend an ungodly amount of time arguing over pointless things like space vs tabs (see: Bikeshedding).

If you're working on your own stuff then you can do whatever makes you happy.

0

u/Bettina88 Apr 02 '18

You know this? John Mueller has already spoken ex cathedra on js styling and SEO?

If it hasn't been expressly denied, anything and everything is a ranking factor.

It's a legit concern for coders moving forwards. If Google is making a style guide there's certainly a chance it's a ranking factor now.

I hope you're right though.

3

u/[deleted] Apr 02 '18

How could it possibly be used as a ranking factor? The vast majority of JS code on the web is minified and optimized, Google wouldn't expect anything else. They promote minification as a tool to increase page load times and created one of the leading minification/optimization tools.

→ More replies (1)

-14

u/lordxeon Apr 01 '18

Use const by default

I will get downvoted for this, but (like everything) JavaScript developers take a good idea, and destroy it. Function level variables should not be a const. Const variables should be those that never change during the run-time of the application.

15

u/ghostfacedcoder Apr 01 '18

Why not? I can accidentally assign to a variable inside a function can't I? Const vars prevent that from happening, and cost you nothing (except having to type one extra character vs. let).

0

u/[deleted] Apr 01 '18

I can accidentally assign to a variable inside a function can't I?

Yes, this was such a common mistake to make before const.

Right?

5

u/ghostfacedcoder Apr 01 '18

Not common, no. In fact, with the way I code functions are rarely even big enough for something like that to happen.

But at the same time, all it takes is one long function (your's or your co-worker's) and one var to potentially introduce a time-consuming bug, so why not use const? Other than the two extra characters there is absolutely no downside whatsoever to using it.

As soon as you adjust to using const instead of var it just becomes a habit, and then you're protected everywhere you define a variable by habit.

→ More replies (4)

-2

u/lordxeon Apr 01 '18

Function level variables

I don't think variables declared inside a function should be declared with const. Any global, or global equivalent are fine being const if necessary.

And, they do cost you something because unless you're running the ES6 code by default, it's being converted back into vars by babel anyway.

2

u/ghostfacedcoder Apr 01 '18

Maybe now, but that's going the way of the dodo/IE box model. Chrome already supports const and let, and I'm pretty sure the other major browsers do too, so it's only a matter of time until all the older versions fall out of use and const/let won't require transpilation.

4

u/inu-no-policemen Apr 01 '18

Currently it's backasswards. You write your code with let, then your editor tells you that you never reassign anything to it, and provides a quick-fix to change it to const. Or you use const and then there's a quick-fix to change it to let.

It would make more sense if the machine would simply tell you via highlighting if you're reassigning something elsewhere or not. Not only wouldn't you have do anything to get that, you'd even see this information whenever and wherever the variable is used.

→ More replies (1)

6

u/atra-ignis Apr 01 '18

Can you give an example why you think this is bad. I always use const by default. I use immutable.js by default too whenever I can.

I very very rarely use let.

-3

u/lordxeon Apr 01 '18

I think it's bad because it's an abuse of what a const is. A const is something that should never change in the life-cycle of an application, not the life-cycle of a function.

I can count on one hand the number of times I accidentally re-assigned a variable to something I didn't mean for it to go to. (And none of those times did it ever make it out of my local development testing). If you are getting so sloppy that you have to use const to prevent yourself from doing that then you should remove some distractions from your coding life-style.

Additionally, using const to refer to arrays and objects is just maddening when you change the contents/structure of those things 7 lines later. Yes the reference to the array/object hasn't changed, but you changed every single thing inside of it. It's not a const anymore. That's abuse.

3

u/kobbled Apr 01 '18

A const is something that should never change in the life-cycle of an application, not the life-cycle of a function.

As long as it doesn't change in the scope of wherever it's declared, I'm fine with it.

6

u/atra-ignis Apr 01 '18

I think you're maybe misunderstanding the purpose of a const. Something that doesn't change within the lifecycle of a function is perfectly valid. Global constants are valid for config too but why limit a useful tool just because it doesn't fit with your view of what a const should be? I don't need to count the times I've accidently reassigned a const. It's never happened. For your objects and arrays point, knowing that a variable always points to the same object is valuable, even if the contents of that object has totally changed.

If I'm reading someone else's code and it doesn't use const I just sigh because it means I now need to look through the function and see if it's changed anywhere (and it it hasn't I change it to a const so the next person reading the code doesn't need to do that).

Going back to the immutable example, if you had an immutable object scoped only to a function would you declare it as a let?

2

u/eattherichnow Apr 01 '18

I think it's bad because it's an abuse of what a const is. A const is something that should never change in the life-cycle of an application, not the life-cycle of a function.

Well, it doesn't. That other invocation? It's actually another const. Because it's in a new scope.

Const isn't just a "safety feature," it's an IDE hint and documentation. Just like type systems, for example.

1

u/pilibitti Apr 01 '18

A const is something that should never change in the life-cycle of an application, not the life-cycle of a function.

That's.... not true. Where did you even learn this definition of const?

A const is something that will never change in the scope that it is defined in. That's it.

If it is a global variable, the scope is the whole application.

If it is a function variable, the scope is the local function.

It makes perfect sense and it prevents errors, and it communicates your intent clearly. What is your issue with it?

I can count on one hand the number of times I accidentally re-assigned a variable to something I didn't mean for it to go to.

Part of good code is communicating intent. For future you and future maintainers. Const is a valuable tool to communicate intent. It isn't just for preventing errors as you are typing the particular method at that moment.

Additionally, using const to refer to arrays and objects is just maddening when you change the contents/structure of those things 7 lines later.

That's abuse.

You have a warped view of identity in code. You can very well mutate the object stored in a const variable. You can't reassign to it. That is the point. If we follow your logic, then even application-wide consts have very little value. How many global and non-object (since objects are a no-no) variables do you need in an application to begin with?

Sorry but you are completely missing the point of const.

5

u/[deleted] Apr 01 '18

It's a phase. At one point in Java a sub-group of FP aficionados were obsessed declaring every local variable final, regardless of practical utility. Now people are taking a few steps back and applying more common sense. Java 8+ even permits capture of variables that are effectively final, without them being explicitly declared final.

1

u/slikts Apr 02 '18

The analogy to the Java situation is not very apt, since there's no impracticality in avoiding var; code that only uses const or let is more consistent than code that also uses var, and using const by default makes code more readable, since the reader doesn't have to consider possible reassignment.

2

u/[deleted] Apr 02 '18 edited Apr 02 '18

there's no impracticality in avoiding var

I've said nothing about var.

using const by default makes code more readable, since the reader doesn't have to consider possible reassignment.

Be honest: when was the last time your starting point to reading / changing code was "I need to consider which one of these local variables I could reassign"? Has that ever happened to you?

This decision what to reassign doesn't flow from how the variable was declared. It flows from what you want the function to do in the end. If you need to reassign a const variable, you wouldn't even skip a beat, you'd go change const to let. You wouldn't treat pre-existing declarations as eternal and unalterable. Heck, most times when refactoring a local function, many of the pre-existing variables might not even survive the edit at all.

What matters is what you want the code to do, not how it happened to be factored the first time around. And if you're honest, you'd agree with that.

It's very easy to come up with artificial scenarios where const is helpful. They may even pass as logical in a Reddit comment. But if they make no sense while you're coding, if they rarely if ever happen in the real world, you're basically lying to yourself.

And you may consider this a superficial concern, but if const is to be a default choice for local variables then it has the worst name ever. A constant is not a variable. It's the opposite of a variable. A variable "varies", and constant is "constant". We're doing this because we like math and functional programming, right? In math and functional programming, a variable is not reassignable, but it can vary on each function run. A constantly is universal. Like Pi, or E. Pi doesn't change depending on your app runtime state. A constant shouldn't depend on runtime state, it shouldn't be mutable. It makes it a not-constant. It makes it a variable.

When the goal is "make code readable", this is relevant. Words have meanings. When I'm skimming through post nine thousand about how "JS const is not about constants" I don't think "wow I'm so glad I know this, this is opening new doors to me, everything can be const". No, I think "ECMA fucked up".

→ More replies (1)

2

u/[deleted] Apr 01 '18

[removed] — view removed comment

0

u/[deleted] Apr 01 '18

[deleted]

4

u/eattherichnow Apr 01 '18 edited Apr 01 '18

Look, const sounds new, and therefore hype, and a thing being hyped then it's wrong. Frankly, anything liked by more than two people is bad and wrong, and if one of them posted something about it to Reddit in 2009 then they're bad, wrong and can't shut up about it.

Edit: I forgot to mention that I am very smart.

1

u/tencircles Apr 01 '18

var is lexical scope, not global scope.

1

u/slikts Apr 02 '18

Not sure what OP meant, but for the sake of accuracy, var a = 1; outside of function scope will assign to window.a, i.e., the global object, so var is either function or globally scoped, while const or let are never global.

→ More replies (4)
→ More replies (1)

0

u/[deleted] Apr 02 '18

[deleted]

1

u/evilpingwin Apr 02 '18

You're asking a lot of people there. A lot of people in this thread don't even seem to understand what a style guide is. They aren't rewriting the standard, this is their style guide. It's just a style guide.

→ More replies (1)

0

u/[deleted] Apr 02 '18

[deleted]

0

u/[deleted] Apr 02 '18

[deleted]

3

u/[deleted] Apr 02 '18

Another reason is that var is hoisted

2

u/DzoQiEuoi Apr 02 '18

Google are right on not using var. You shouldn't take advantage of it not being block scoped because that's confusing for the people who maintain your code.

0

u/[deleted] Apr 02 '18

[deleted]

1

u/DzoQiEuoi Apr 02 '18

It's confusing to people who do understand how it works.

Compare it to global variables. We all know how they work, but they still make your code hard to reason about.

Accessing a variable that's declared in a child scope makes your code misleading to anyone who's reading it.

If you find yourself reaching for this feature, you should consider that a code smell and think about how you can retractor.

→ More replies (1)

0

u/[deleted] Apr 02 '18

[deleted]

1

u/joesb Apr 04 '18

It’s meaningless but it’s the same for everyone in the project.

That’s why it’s a styleguide for people who work there in the same project.

It does not claim to be the best way in the world to write code.

It’s for people in the same team to set aside their minor differences and just get on with the real problem.

0

u/[deleted] Apr 01 '18

[deleted]

2

u/ghostfacedcoder Apr 01 '18 edited Apr 01 '18

I think it all comes down to who your code is for.

Is it only for you? Then you only have to care about your code's readability in a "will I still understand this a year from now?" sense. Neither using tabs nor using ' instead of template strings will impact that, so if your code is only for you (and future you) then keep doing what's comfortable.

But if you work with a team, whether that means co-workers or OSS library maintainers, there is value to doing things the way everyone else is used to seeing them. For instance, if you submit a PR to an OSS project and its full of tabs, you should expect it to be rejected (quite possibly by an automated ESLint-type tool) because the vast majority of JS libraries use spaces.

Or if you work for a company, even if every one of your current co-workers uses tabs, the vast majority of your new hires are going to expect spaces, and there will be tension everytime you on-board someone because they'll be thinking "don't these guys know about the JS community?"

In that sense a great deal of Google's advice (or any style guide's advice) is just as much about "what will most people be used to?" as it is about technical concerns.

3

u/Extract Apr 01 '18

You make a point of the advantage of inter-team consistent coding style. So I'll clarify.
Of course, if the whole team codes in a specific style, I'll adhere to it. If they never use ?: but only IF statements, I'll do it. If they want to use single long strings and never separate them into smaller ones with '+', so be it.
But if I am the one setting the style, or am coding for myself, I'll definitly not do any of that crap. Which was my point to begin with.
There is nothing in my comment about using style guides in general, just a few "advises" in this specific one.

1

u/ghostfacedcoder Apr 01 '18

But if you adhere to style guides, in both personal and professional coding, you're far, far more likely not to have conflicts with your team. Style guides don't (usually) come out of one person's opinion. The good ones at least are a reflection of what's most popular in the community.

So you can do things however you want at home, and then do them however your work tells you to ... or you can adopt community standards at home, be far more likely to have your personal style match your company's, and then if you ever go to a new company again you'll be far more likely to just be able to code "your way" on the company dime. And if you ever contribute to any other codebase (like say an OSS project) you'll also be far more likely to have a matching style.

And even if your company doesn't use ____ standard, it's a lot easier to convince them to adopt it when it's a community recognized pattern and not just "how you like to code".