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?

11

u/Omnicrola Apr 01 '18

I get that people have strong opinions, but I don't get it either. I really, really don't give a shit. My priority is consistency. Which means whatever my IDE does when I tell it to auto-format, that's fine. I have more productive things to focus on.

→ More replies (1)
→ More replies (9)

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.

1

u/ErroneousBee Apr 02 '18

Don't use tab key anymore, almost every language I use now has an IDE that formats well enough that I use that over hand formatting.

Ctrl-shift F every few lines.

1

u/KyleG Apr 02 '18

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.

This is a very compelling argument for why you should use tabs and not spaces. It's not a compelling argument for spaces instead of tabs. In fact, it's a damning argument against spaces. If it just remained a tab and then you had your IDE make your tabstop whatever you wanted, it's a non-destructive UI change.

Converting tabs to spaces is like working with a single layer in Photoshop. NO.

2

u/gougs06 Apr 02 '18

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

2

u/calligraphic-io Apr 01 '18

Not that this issue hasn't been hashed to death on the interwebs, but:

I use vim in the console often for editing code files. Line width is limited; default is 80. Using four spaces force many lines to wrap, which makes code very difficult to read.

1

u/cresquin Apr 01 '18

Tabs don’t render well in VIM tools that have terminal driven error messages that point at code.

I personally prefer tabs because they’re semantically correct.

-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.

1

u/sr-egg Apr 02 '18

That’s my point, everyone in this sub is a moron and you should do the opposite.

18

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

...

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

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.

3

u/lhorie Apr 02 '18

IMHO, if you don't want listicles in your platform, you should reject them. If editing is a thing, then who owns the copyright? From the author's comments, it seem like he wasn't aware of the editing arrangements. As a reader, I'm now not going to trust that what is written in your platform is 100% from their authors (and at that point, I might as well be reading fake news in Facebook). You absolutely need to be transparent about this stuff.

2

u/timeparser Apr 02 '18

Thank you for clarifying this, /u/quincylarson. I understand why you did this, but the word “lesson” might have mislead the reader – especially novice developers.

There are many developers out there who treat tech giants like Google like they are the “maximum authority” in how to write software.

While Google has certainly world-class engineers that have the necessary collective wisdom to share best practices with the rest of the community, it is important to understand that this is an organization-level style guide and that every piece of advice should be taken with a grain of salt.

No organization is the same, Google is not perfect (although they are certainly good), and most importantly, their opinions are not standards.

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.

1

u/[deleted] Apr 02 '18

I know one of the community managers; I don't know if it will help — even remotely — but I can mention it to him next time I see him.

1

u/codefinbel Apr 02 '18

Do you know if this is for vanilla only, don't see how using React would be possible without import and export statements? (Unless I'm missing something)

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.

2

u/Disgruntled__Goat Apr 02 '18

it's also a reflection of the opinions of thought leaders in the JS community

How do you know?

0

u/[deleted] Apr 02 '18

[deleted]

2

u/[deleted] Apr 02 '18

It's not about the install base but number of executions per user but he's still wrong.

However if it were IE and Apache in the mid naughties he wouldn't be though. But by your metrics he would be. It's just not applicable when comparing client and server software.

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.

2

u/xtr3m Apr 01 '18

Well, it's one way of doing things and if no other company or organization propose something similar it will become the standard.

1

u/[deleted] Apr 02 '18

Actually Airbnb style guide is already a de facto standard. Personally I prefer low semicolon styles like Standard so I don't care about either but coming up this late in the game while there's an established standard (that only differs in minor cosmetics, and even there it goes against what top 3-4 preferred style guides do), I don't think that even being by Google will help that much. Surely this will have a lot of fans and projects, but I don't see it dethroning Airbnb.

1

u/0987654231 Apr 02 '18

To be fair the google style guide isn't new, we've been using it since like 2011. We also use Airbnb now for what it's worth.

1

u/eterevsky Apr 02 '18

Some of these rules are introduced not because they the ultimate “correct way”, but just to keep Google’s own code base consistent.

1

u/timeparser Apr 02 '18

I know. I was pointing out the misleading title.

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.

1

u/CiezkiBorsuk Apr 01 '18

IDK about that. Even once we have full support everywhere, I'd rather use CommonJS-style modules.

They work just fine and are widespread. Switching to new system now causes chaos (i.e. a package you want might not yet use native modules, so you don't get to use it, or at least not smoothly).

I don't hate native modules, I just don't see why bother when we have a good, working solution.

10

u/TallSkinny Apr 02 '18

To be fair, they're not exactly the same, since commonjs imports are dynamic and es imports (aside from import()) are static. That opens up a lot of opportunities for tooling (like tree shaking, iirc) that aren't really an option when dynamic importing is the default.

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.

15

u/hyperhopper Apr 01 '18
var a = 5
var b = 10
[a, b] = [b, a]
console.log(a, b)

Then add semicolons to make it work like it should

3

u/Voidsheep Apr 02 '18

Pretending ASI doesn't exist is also dangerous, it's not like you can disable it.

function shouldHitTheBrakes() {
  return
    isSmeoneOnTheWay ||
    isTurnAhead ||
    isAboveSpeedLimit
}
→ More replies (1)

11

u/allenthar Apr 01 '18

Okay.

var a = 5 var b = 10 ;[a, b] = [b, a] console.log(a, b)

I have literally never had this situation come up while coding JS, and I’ve been doing it full time for a few years now.

Regardless, Prettier handles automatically removing or adding semicolons to my code. So it’s literally just a linter setting at this point.

→ More replies (5)

5

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

...

3

u/nayocum Apr 01 '18

If you use an IIFE it can cause issues if your last line didn't have a semicolon as well

→ More replies (3)

5

u/aaarrrggh Apr 02 '18

Is this a joke?

I’ve not been using semi colons for over a year on personal projects.

Number of bugs caused by this decision: 0.

0

u/[deleted] Apr 01 '18

[deleted]

10

u/Mingli91 Apr 01 '18

Yeah, been using Standard JS since my last job and I love it. Not had a single bug from omitting semicolons and now I have a far better understanding of ASI in JavaScript

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)

-15

u/brokenURL Apr 01 '18

Boooooooooo

→ More replies (12)

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.

3

u/ghostfacedcoder Apr 01 '18

I could have stated it more clearly (I sort of conflated W3C and browsers, when what I was just talking about the version both support), but what I said wasn't incorrect. The version of ES Modules decided upon by the W3C does define that the modules work in in such a way that the only possible way (according to the Node engineers at least) for Node to implement that spec is to use the .mjs nonsense.

3

u/Meefims Apr 02 '18

The W3C isn’t part of this. The new extension is really fallout from various complex scenarios in which CJS modules and ES modules include each other in Node. Browsers have a similar problem but they solved that with type=“module” in the script tag.

0

u/[deleted] Apr 01 '18

[deleted]

3

u/ghostfacedcoder Apr 01 '18

Probably, but I don't know it :) I just read /r/javascript.

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.

1

u/[deleted] Apr 02 '18

Also, var is hoisted

1

u/[deleted] Apr 03 '18

[removed] — view removed comment

2

u/[deleted] Apr 04 '18

Hoisting is like declaring the variable before everything else. It lets you do stuff before a variable is even declared. Const and let are not hoisted so it makes sense in that you can't do anything with them above where they are declared.

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

1

u/evenisto Apr 02 '18

It's great, but I always end up overriding so many rules...

1

u/colbycheeze Apr 02 '18

Ya i built one that extends it and has just a few overrides that everyone here at amazon is starting to use (within ads org)

Sometimes it also can be project based for the minute things. It really does help a lot with the react rules though.

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.

7

u/RabSimpson Apr 01 '18

Only in the case of client-side code. Who minifies server-side code?

→ More replies (16)

2

u/KyleG Apr 02 '18

YES FRIEND

God how many freaking times have I run into problems because some ASS did a 3-space indent or something and my IDE converted some but not all the 3-space indents into 4-space indents to make it conform with our style but it missed some because SPACES SUCK, USE TABS WARBLGARBL then everyone gets to set their own indent levels!

I like my tab to be 4space widths in some languages and 2space widths in others

like 2 space in JSX is way better than 4 space, but 2 space in Python or JS is TURRIBLE

1

u/monsto Apr 02 '18

*turble

2

u/Tyreal Apr 02 '18

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

0

u/[deleted] Apr 01 '18

[deleted]

11

u/DzoQiEuoi Apr 02 '18

If there's a deep if-chain the problem isn't 2 space indentation.

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.

1

u/joesb Apr 04 '18

let’s behavior is the preferred choice compare to var in most cases. It’s lexically scoped.

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.

1

u/ComfortableDay7607 Sep 24 '22

ITT: people who believe style guide is supposed to match all their preferences or it’s shit. ..@[email protected]/GOOGLeads

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.

23

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

...

5

u/oweiler Apr 01 '18

Well it can be configured to convert a tab to 4 spaces.

20

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

...

5

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

Tabs to spaces is easy, the problem is for a block of code how does the editor know when 2 spaces was supposed to represent indentation vs alignment:

function() {
SSwhile(value) {
SSSSif(reallyReallyReallyReallyLongConditionA &&
SSSSSSSreallyReallyReallyReallyLongConditionB &&
SSSSSSSreallyReallyReallyReallyLongConditionC) {
SSSSSSSSreturn;
SSSS}
SS}
}

function() {
Twhile(value) {
TTif(reallyReallyReallyReallyLongConditionA &&
TTSSSreallyReallyReallyReallyLongConditionB &&
TTSSSreallyReallyReallyReallyLongConditionC) {
TTTSSreturn;
TT}
T}
}

In the latter case to go from indentation width 2 to 4 the editor simply makes tabs display twice as wide and everything is good. If the editor tried to display 2 spaces for every space from the start of a line then the if conditions would lose their alignment with the opening of the statement.

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.

1

u/seands Apr 01 '18

Why is it dumb?

3

u/ssjskipp Apr 02 '18

Because your project so have an .editorconfig file which is widely supported, and most ide have a setting for whitespace width, making the problem moot

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

1

u/Disgruntled__Goat Apr 02 '18

Copy-pasting tabs works perfectly fine on SO. And if everyone uses tabs everywhere, including displaying code, you could more easily copy-paste it from SO into your editor without having to worry about 2-space vs 4-space etc.

0

u/[deleted] Apr 01 '18

[deleted]

→ More replies (1)

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)

2

u/Mingli91 Apr 01 '18

Using template literals says to someone reading your code that there is a variable about to be interpolated and it tells the JIT compiler to prepare to do something other than just create a string. It's not huge, but there are reasons not to use them blindly that are more than personal preference.

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

2

u/wavefunctionp Apr 01 '18

I agree. I don't care about too much about style. I just prefer not to be too weird, easy to change/diff the code, like dangling commas, and automated through the editors on save or with a hotkey.

1

u/tencircles Apr 02 '18

it's definitely not "preferred". People who use them are very vocal about it though. I haven't seen anything indicating that single quotes are preferred.

→ More replies (1)
→ 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)

1

u/shaggy756 Apr 01 '18

Yeah anybody arguing that it's faster is full of it.

→ More replies (3)

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

0

u/Wooshception Apr 01 '18

Single quote is arguably faster to type since it’s a key that doesn’t require modification. The difference in speed may be tiny but adds up quickly for something typed potentially hundreds of times a day.

Embedded quotes are relatively rare and from my experience occur only slightly more frequently than embedded double quotes.

→ More replies (2)

0

u/[deleted] Apr 01 '18

[deleted]

3

u/tencircles Apr 01 '18

you'd use backtick in modern JS for these cases.

2

u/masklinn Apr 02 '18

That's one thing which almost never happens. Meanwhile single quotes in text are extremely common (apostrophes).

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 [email protected]/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?

1

u/Bettina88 Apr 04 '18

In the same .js document, no. But in the same project? I really don't care.

2

u/joesb Apr 04 '18

So you are just waiting for someone to fuck it up. Instead of agreeing with the team once.

2

u/Bettina88 Apr 04 '18 edited Apr 04 '18

Honestly, when people say things like this it makes me wonder if they've ever worked on a large, distributed Javascript project.

There's code from dozens of sources, repos and libraries incorporated in every large project. You'll be editing code written by hundreds of different people.

You want to force a rigid, pointless indenting standard across hundreds of individual .js files?

Jesus, if your coders can't open a file and instantly see what the indentation (or function bracketing, or object structure) standards are and adapt to that individual .js file... then maybe get some actual coders and stop hiring interns.

This is like arguing about which end of a hard boiled egg to start on.

What we have here are Google style weenies being Google style weenies and trying to keep their jobs.

→ More replies (7)

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.

→ More replies (3)

-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)
→ More replies (2)

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.

→ More replies (5)

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)
→ More replies (10)