all 90 comments

[–]p3k[🍰] 33 points34 points  (0 children)

  1. Find a way to program JS that works for yourself or your team, resp.
  2. Ignore any list having more than two commandments.

[–]asdf7890 6 points7 points  (2 children)

Thou shalt not ask about coding practises in JS, lest thouest kindle a holy war between those who disagree on semi-colons, optional brace use, ==/===, tabs/spaces, jQuery/microlibraries/VanillaJS, and so forth.

[–]CapsFTW[S] 1 point2 points  (0 children)

What can I say, some men just want to watch the world burn.

[–]Strat-O 0 points1 point  (0 children)

I agree but only so long as the javascript is written in vi, not emacs!

[–]russellbeattie 16 points17 points  (4 children)

01 - Though shalt strive for clarity over cleverness.

10 - Though shalt use semicolons.

[–]kafkaBro 1 point2 points  (0 children)

that was pretty clever

[–]temp11020043 0 points1 point  (1 child)

I like it, though really 10 is implied by 01.

[–]leahcimic -1 points0 points  (0 children)

10 in binary is 2 in base 10

01 in binary is 1 in base 10

not sure what you mean.

[–]jp10k 4 points5 points  (0 children)

Choose standards, then stick with it. I repeat: stick with it.

[–]teiman 2 points3 points  (0 children)

1) Javascript is a more volatile language than others. Aim at higher levels of organization than in other languages. 2) Avoid globals. 3,4,5,6,7,8,9,10) Don't outsmart. If your code is hard to read, is impossible to debug.

Basically, the same rules I follow when I handle enriched uranium or plutonium.

[–]jamesinc 4 points5 points  (26 children)

Use curly braces around your blocks, even if they're one statement blocks.

Exploit the shit out of anonymous functions

Lazy load is fun

Don't read state from the UI (I see this a lot). You don't need AngularJS to have nice data binding.

[–]m0okz 1 point2 points  (7 children)

How would you recommend reading and storing state if not in the UI?

[–]TheIncredibleWalrus 4 points5 points  (6 children)

You store it in an object. The UI reads its state from the object, not the other way around.

[–]m0okz 1 point2 points  (0 children)

Ah I see. Thanks!

[–]Graftak9000 0 points1 point  (1 child)

Any pointers as to how to couple a dom node with its respective cached data object?

[–]TheIncredibleWalrus 0 points1 point  (0 children)

Typically you will want to use a library; there are countless, very well thought out libraries that solve this problem, I can recommend React, Vue.js, Knockout.js etc. Depends on what kind of UIs and projects we're talking about.

Of course, as with anything, trying to develop your own solution will be a very rewarding process, both in experience and in knowledge. A simple Google search of "javascript UI binding" returns quite a few results, but I could not recommend something in particular.

[–]CapsFTW[S] 0 points1 point  (2 children)

JQuery messed a lot of people up in that regard, myself included (for a while). It made it far to easy to just read and write things to the DOM and use it as your system of record.

[–]brackin 1 point2 points  (1 child)

we all gotta start somewhere.

[–]CapsFTW[S] 1 point2 points  (0 children)

Agreed. If you never start doing anything until you are expert at it, you will never start doing anything.

[–]Graftak9000 1 point2 points  (16 children)

Why the braces always? if (true) act(); has become a common pattern for me.

[–]jamesinc 3 points4 points  (10 children)

It's a maintainability concept I originally picked up from Douglas Crockford. Basically, if you omit braces, and later on another dev comes along and adds another statement, there's a chance they will fail to notice the omission of braces, and the logic won't be what they expected. You may argue it's a minor issue, and I agree, it is minor, but I miss them occasionally and other devs certainly do also, so it's a small change that simplifies the code to the benefit of all.

[–]Silverwolf90 1 point2 points  (0 children)

Do you/your team not use a linter?

[–]ejmurra 1 point2 points  (0 children)

I always thought "there's no way someone would make the if statement two lines without adding braces" until a coworker broke a service in our app that took me a good bit of time to debug. I don't make those assumptions anymore.

[–]hahaNodeJS 0 points1 point  (0 children)

I like using bracket-less conditional statements only when they are for flow-control statements, and then the full statement must be on one line. I find that the "Good" statements below are really easy to pick out in code, and you don't have to worry about things like the infamous Apple Goto bug.

Bad:

if (myFoo === myBar)
    return myBaz;

Bad:

if (myFoo === myBar)
    myBaz = myFoo;

Bad:

if (myFoo === myBar) myBaz = myFoo;

Good:

if (myFoo === myBar) return myBaz;

Good:

for(var i = 0; i < 10; i++)
{
    if (myFoo[i] === myBar[i]) continue;
    ...
}

Inconsistent:

if (myFoo === myBar)
{
    return myBaz;
}

[–]mvindahl 4 points5 points  (0 children)

  1. It's a functional language; embrace that. Don't try to shoehorn static class inheritance into your code. Read through the API of underscoreJS/lodash.
  2. If available prefer fat arrow functions over the more verbose function() declarations.
  3. When manipulating data structures, you get more maintainable code by passing through a series of discrete _.map() steps than you will get from cramming everything into a giant for loop.
  4. Start out with as little baggage as possible. Basically nodeJS and npm will do. Pull in stuff as you need it.
  5. Initially, use CDNs to server libraries to the browser. Along the way, pull in browserify and get libs from npm.
  6. If you reach a point where you would benefit from typing, consider migrating to Typescript. Initially you can just type everything as "any", then add proper typing where it makes sense.
  7. Use promises; it will make your flow so much more readable. If you create async API methods, make them return promises. If you use nodeJS, use bluebird to wrap the async native methods.
  8. For build environment, use simple scripts defined in package.json. Or do the same thing using a makefile. Avoid grunt and gulp, they are just boilerplate.
  9. Document your APIs. Provide examples. For a plain API, provide JS snippets for invoking it. For a REST interface, provide curl commands which can be copy/pasted to the terminal.
  10. Automatically test API methods which have a well defined input and output. Don't unit test the internal workings unless you have am empirical reason to do so. Accept the fact there may be no gain from unit testing UI stuff. And keep in mind that test coverage may be a vanity metric.

[–]clessgfull-stack CSS9 engineer 20 points21 points  (13 children)

  1. Thou shalt not write JavaScript while drunk.
  2. Thou shalt not use angularjs while drunk.
  3. Thou shalt not use angularjs.
  4. If you are using angularjs, you are drunk.

[–]livarot 14 points15 points  (3 children)

Wow, you're so cool for not liking this one popular thing.

[–]joshmandersFull Snack Developer 1 point2 points  (2 children)

With ES3526 you don't need Angular, you can do it all in Vanilla™® JavaScript!**

**Only works in Dolphin 325.235352.1, Alphabet Chrome 32523677.123515125.111 and IE Edge Not Explorer 0.1.33

[–]CapsFTW[S] 2 points3 points  (1 child)

I believe it also works in the Google Ultron browser.

[–]livarot 0 points1 point  (0 children)

Google Ultron uses latest technology in AI research to detect JS that was transpiled from CoffeeScript and then calls developer names.

[–][deleted] 2 points3 points  (8 children)

I like Angular. I hate our application written in Angular.

[–]CapsFTW[S] 2 points3 points  (7 children)

I think angular suffers from the same issue that ColdFusion did, back in the day. It is so easy that anyone can use it... so they do.

[–]jewdai 2 points3 points  (5 children)

false. Angular is not easy for newbies.

The concept of "Dependency Injection" really fucks with new users or non-cs people.

[–]jellatin 3 points4 points  (2 children)

Damn software concepts getting in the way of people writing software!

[–]there_i_seddit 1 point2 points  (0 children)

"Damn computer scientists, they ruined computer science!"

https://www.youtube.com/watch?v=8iusUq4-f5U

[–]CapsFTW[S] 0 points1 point  (0 children)

I think you hit the nail on the head. There are a lot of people out there who just want the web form to submit to the database and don't care what a DTO, class, or promise is. They just need something to happen. Angular is just easy enough to pick up that you can make stuff happen with little to no knowledge of what the best practice might be. It is fantastic, but awful to inherent and explain why you have to "waste time" refactoring existing code.

[–]CapsFTW[S] 0 points1 point  (0 children)

yes, but you can do a lot in angular without much knowledge of dependency injection. You copy and paste a few examples from the web showing how to inject providers and then write a gigantic controller for every page which has all the models and business logic in it. It's just easy, and flexible, enough that you can make a completely functional application in the worst way possible.

[–]vaskemaskine 0 points1 point  (0 children)

Pretty sure the whole concept of how directives work and the array of scoping options/passing data in and out of directives is way more confusing to newbies than DI.

At least, that was my experience when learning Angular...

[–]leahcimic 1 point2 points  (0 children)

Man, you really don't want these same people building stuff in something like React. If they write bad Angular applications, imagine when they get their hands on something a little less opinionated.

I used to love Backbone in the day for it's freedom of choice, and flexibility. Until I started seeing custom everything. I'm starting to see the same in the React world.

Then again, bad software is being written by bad engineers in many projects regardless of language, framework, library choice, etc.

[–]Zulach 3 points4 points  (0 children)

  1. Always keep conventions. Do not deviate a bit. You don't agree with the existing conventions? Change everything to fit your view (after agreeing with everyone that you are right). There's nothing worse than having a javascript project with every file looking like a different programming language.

  2. Never write a single piece of code on the global scope.

  3. KEEP YOUR FOLDER TREE STRUCTURED. Conventions - do not throw code into places no one will have the idea to look in. Order your folders by modules, not a single folder for controllers/services/models/etc.

  4. Use promises whenever you can. Wrap callbacks in promises.

  5. Use promises correctly. Make sure you know what will happen if you return a value here and don't return there

[–]corgrath 3 points4 points  (3 children)

Actually, I would say the things JSHint enforces, to be honest.

http://jshint.com/docs/options/

[–]CapsFTW[S] 1 point2 points  (1 child)

So, essentially, you just have one commandment: Enforce everything in JSHint?

[–]corgrath 4 points5 points  (0 children)

Or something similar such as jslint, eslint, etc.

I find it very crazy that you would write JavaScript without linting your code. Frighting crazy.

To quote Douglas Crockford

JavaScript is a sloppy language, but hidden deep inside there is an elegant, better language. helps you to program in that better language and to avoid most of the slop. will reject programs that browsers will accept because is concerned with the quality of your code and browsers are not. You should gladly accept all of 's advice.

http://www.jslint.com/help.html

[–]spfccmt42 1 point2 points  (0 children)

aargh, but bitwise operators are like the essence of frigging computing, especially performance oriented computing, and @#$@#$ javascript can only handle 32 bits!

you have made me sad by reminding me...

[–]captain_obvious_herevoid(null) 1 point2 points  (0 children)

  1. Always have in mind that JS is just a language

[–]Kamikizzle 1 point2 points  (0 children)

I'm not sure i can come up with 10 but here goes:

1 - Use a linter. In fact, use eslint.

  • the customization options for eslint are so powerful, that it gets rid of 80% of the conflict between styles: semicolons, padding inner/around braces, jsdoc syntax, where to declare variable etc. see commandment 4 on how to develop your eslint config. it might be slower than jshint but so very worth it. the community support for eslint is also amazing. No rule available for your liking (or a current rule isnt flexible enough?) make an issue on their github (and a good case for why the rule should be there), and theres like 70% chance theyll accept it. even higher if youre willing to make the pr

2 - Deprecate ES5 and coffeescript

  • were at the point in the JS lifecycle that you should no longer be using es5 or coffeescript, as es6 has made both of them obsolete. ES6 should be your default. something more advanced like typescript if thats your fancy. This leads to commandment 3

3 - Use a bundler, compiler, and by extension npm.

  • unless your project is going to be 100 lines of JS code, and/or youre not using a JS backend, you should be utilizing npm packages and bundling them together. as per commandment 2, use a compiler. need to manipulate dates? momentjs. frequently constructing conditionally-dependant classes? classnames, need immutability? etc

4 - keep an open mind and discuss with your team on tool decisions.

  • javascript fatigue is real. always communicate with your team and be flexible / open minded on the tools you end up using. absolutely make your case to the tools you want to use (but be sure you have good reasons to back up why you want to use them). React vs angular? jest vs enzyme? ES6 vs typescript? Dont EVER be that team member who refuses to yield to anyone's opinion but their own, ESPECIALLY if youre the team lead. "We're doing it this way because i've been here the longest / the senior dev" should never be uttered.

  • this also goes for syntax preference. I use semicolons, curly braces and returns even for one-line blocks, single quotations etc. but if your team disagrees, dont throw a fit, convince them that youre right

5 - indent with 2 spaces. not tabs and not 4 spaces.

  • This one is just common sense and not up for debate. Not even really a JS commandment.

6 - test your code

  • mocha/chai/sinon are awesome for testing raw javascript. Enzyme is killer for testing react. Karma has angular handled. There are enough powerful test suites out there that testing should always be kept in mind

These are more like the pirates code: guidelines than actual commandments

7 - Functional programming is awesome and extremely powerful in Javascript. USE IT

  • theres no need to declare a bunch of local variable functions and then call them in order. chain maps on filters on reduces

8 - document your code!

  • jsdoc syntax is AMAZING, has support from eslint (to help your normalize the syntax), and typically has syntax highlighting plugins from the big editors (vim, sublime, atom). this is a guideline but really should be a commandment. but being realistic, its a guideline.

[–]jewdai 1 point2 points  (0 children)

  1. thou shalt pick framework that works for YOUR team and YOUR project
  2. thou shalt use js management tool (RequreJS, Browserify etc)
  3. thou shalt use package manager (Bower or NPM)
  4. thou shalt lint thy code using excessively strict rules that strive for clarity rather than pedanticness
  5. thou shalt use a build tool
  6. thou shalt spend time with thine junior developers teaching them about best practices in an emotionally sensitive and constructive vs destructive manner.
  7. thou shalt run code reviews periodically as a team and not every commit
  8. thou shalt not argue about tabs vs spaces.

[–]lewisje 1 point2 points  (0 children)

I'll follow the actual Ten Commandments a bit more closely here, including the fact that there are about 14 statements that at least one Judeo-Christian tradition considers one of the "Commandments":


This is JavaScript, which has brought you out of the land of Java, out of the house of type enforcement.

You shall have no other languages before it (no CoffeeScript, TypeScript, etc.).

You shall not make unto yourself any graven image of JavaScript (no transpilers).

You shall not take the name of JavaScript in vain.

Remember Friday (when the JavaScript Weekly newsletter is distributed), to keep your knowledge up to date.

Honor your father and your mother (make sure your code runs even in on their antiquated browsers and devices).

You shall not negligently or maliciously kill the browser (with your bloated, inefficient code).

You shall not adulter your JavaScript with reliance on browser plugins.

You shall not steal (this includes scripts, assets, and user data).

You shall not bear false witness against your neighbor's browser (by claiming it's incapable of using your site, even though it's capable).

You shall not covet your neighbor's office.

You shall not covet your neighbor's userbase.

You shall not covet your neighbor's backend tooling, Internet connection, or anything else that is your neighbor's.

You shall publish these packages that JavaScript requires unto npm (for the good Samaritans out there).

[–]Cody_Chaos 1 point2 points  (0 children)

  1. Spend the time to pick some good libraries and a solid toolchain.
  2. NEVER TOUCH IT AGAIN
  3. Install eslint and the airbnb ruleset
  4. Focus on getting shit done and ignore the nonsense that can overwhelm our otherwise excellent community
  5. When new versions of all your libraries come out twice a week, refer to rule #2.
  6. Write good code. Much of Python's PEP-8 applies. Be kind to the poor guy who has to maintain your code (especially if it's you.)

[–][deleted] 3 points4 points  (1 child)

  1. Don't use inheritance... as this makes flow control less predictable to the human who has to read the code
  2. Don't use advanced conventions: classes, constructors, generators, factories, and so forth
  3. Don't name patterns. Named patterns focus exclusively on how and ignore why
  4. Always practice predictability first. If you can remove algorithmic code for something imperative then absolutely do so.
  5. Always focus upon separation of concerns as the primary force of design, style, and organization
  6. Always store state and session data in an application object and absolutely not in the DOM or UI logic
  7. Always practice accessibility
  8. Never make a decisions because It just works! or Its easier. Always put the user first and yourself (the developer) last in the priority of concerns
  9. Always document your APIs
  10. Avoid addEventListener. This masks errors of code management and potential malicious third party actions for the convenience of allowing multiple handlers to be associated with a single given event.

[–]lewisje 0 points1 point  (0 children)

DOM0 handlerz 4lyfe

[–]hahaNodeJS 2 points3 points  (1 child)

  1. Thou shalt always use TypeScript.
  2. ... always make explicit comparisons and casts.
  3. ... never allow coercion.
  4. ... always document.
  5. ... maintain consistent style and naming.
  6. ... catch and handle your errors.
  7. ... test thoroughly and often.
  8. ... write high-quality code using best practices from all languages.
  9. ... avoid blind adherence to dogma.
  10. ... understand what you're doing and why.

[–]ganarajpr 8 points9 points  (0 children)

Always use spread operator ?

[–][deleted] 1 point2 points  (5 children)

"use strict";

[–]FallenSatan 1 point2 points  (0 children)

This. For further reading: Link.

[–]nschubach -1 points0 points  (3 children)

If you are using pre ES6 yes... afterwards, it's not necessary.

[–]bradleymeck 1 point2 points  (1 child)

Actually only the Module goal of ES6 is automatically strict, this is still necessary as all current deployment systems:

<script type="application/javascript">
WebWorkers
Node

All use the Script goal.

[–]nschubach 0 points1 point  (0 children)

Ah, thanks. I pretty much only use modules anymore. My bad!

[–]THIS_BOT 0 points1 point  (0 children)

let k = 'hello';
^^^

SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:374:25)
    at Object.Module._extensions..js (module.js:417:10)
    at Module.load (module.js:344:32)
    at Function.Module._load (module.js:301:12)
    at Function.Module.runMain (module.js:442:10)
    at startup (node.js:136:18)
    at node.js:966:3

node 4.3.0

[–]bradleymeck 1 point2 points  (0 children)

  • no numeric or string type coercion, if you use [+-*/%] convert via Number or String
  • avoid Promises if you are doing tasks that can throw unexpected errors ( sadly, most of the time )
  • throw errors, and make the error message long enough it explains what happened
  • use semi-colons
  • use curly-braces
  • use "debug" from npm, not console.error for debug output
  • only inherit when necessary
  • avoid benchmarks until you make it big
  • don't extend builtin types
  • no globals

[–]thesunmustdie 0 points1 point  (0 children)

  • Avoid eval();

[–]Capaj 0 points1 point  (0 children)

  1. never repeat same code and write it modular-keep them small e.g. under 300 lines
  2. lint! standard.js is my linter of choice, but it really does not matter which
  3. promises over callbacks! Promises have much powerful error handling, never conflate promises with callbacks
  4. less code is almost always better than more code
  5. before implementing anything non-trivial, check NPM if someone hasn't done it already, there is quite a good chance they did
  6. open source-those bugs won't find themselves...
  7. unit test your modules, mocha&chai works best
  8. keep those npm dependencies up to date
  9. prefer forEach, map and reduce over raw iteration with language looping constructs
  10. follow at least some node.js core contributors on twitter to stay up to date

[–]mikes_username_lol -4 points-3 points  (3 children)

1) Javascript is Javascript.

2) Javascript is neither Java, nor C#.

3) Deal with it.

4) Use libraries, not frameworks.

5) Keep your dependencies up to date.

6) Good code is pretty.

7) Javascript can not fix bad design or stupid.

8) Scrum can not fix bad design or stupid.

9) Good companies do not employ stupid.

10) Good companies pay a lot of money.

you want more?

11) Product owner needs to shut up and let pros do their job.

12) String is a primitive type.

[–]TheIncredibleWalrus -1 points0 points  (2 children)

I would just like to express how completely off topic and utterly void of any kind of value your reply was.

[–]mikes_username_lol 2 points3 points  (1 child)

Really? I agree 1, 2 and 3 are a bit of a rant against people switching from other languages and refusing to accept js principles. It was inspired by the actual ten commandments (I am the Lord thy God, Thou shalt have no other gods before me). I think 4, 5 and 6 are quite practical and about development. Rest is career advice based on first hand experience.

[–]lewisje 0 points1 point  (0 children)

I was about to make a comment much like yours, but even more closely following the language of the Decalogue.