Practical Ways to Write Better JavaScript

Ryland G on July 25, 2019

I don't see enough people talking about practical ways to improve at JavaScript. Here are some of the top methods I use to write better JS. ... [Read Full]
markdown guide
 

Great read! While I do agree with you in 90% of what you said, you've explained everything quite clear!
My pet peeve though is asking JS developers to switch to TypeScript. Don't you think TS tries to force an OOP paradigm into JS, which is not necessarily OOP?
Wouldn't you agree that instead of forcing people out of JS's paradigm so they can write better code, it would be better to get them to actually understand JS's paradigm instead?
Just asking to spark conversation, I would love your opinion on it, I was never able to get on board TS or CoffeeScript back then either.

 

You don't have to write object oriented TypeScript. Also, JS is just as much OOP as TS is.

Wouldn't you agree that instead of forcing people out of JS's paradigm so they can write better code, it would be better to get them to actually understand JS's paradigm instead?

TS doesn't change the basic paradigm of JS, it just makes it type safe. Types !== Objects. The only real reason to use JS over TS is that it's slightly (I really do mean slightly) faster in terms of development speed. But that is definitely not worth the loss of confidence and consistency you get with TS.

Check out fp-ts, which brings functional semantics to TypeScript.

I always appreciate your comments Fernando, thanks for sparking a great conversation.

 

Ryland do you consider writing TypeScript for the sake of "type safe" is more advantageous than testing ?

If I had to choose between the two I would choose testing every time. Nothing replaces good tests.

I see, I've never used Typescript before. However, all the arguments presented by people recommending it never convinced me. I think it's kinda useless to switch for TS to only get that compile-time error hinting.

My point is why to switch if you can use the current JS ecosystem to write tests that ensure the outcome ( The business logic ) is valid, and check the types if you want to, rather than adding that semantic analysis provided by TS which gives no extra magic just a hint for the source of type mismatching ( The same as testing ). Really Writing better JS using JS itself, alongside testing, is more appropriate IMO.

JS ecosystem is complicated enough, TS is fragmenting the community.

Typescript and tests cover different failure scenarios. This article was very informative about the benefit of each: css-tricks.com/types-or-tests-why-...

Thanks, it sounds interesting. I'll give it a read

The whole "only being a compile time safety net" is something I told myself before I forced myself to give it a propper go.

The power of being able to refactor a large app without breaking something is invaluable for me.

A good example is the ability to define the type of a return from an API. If this shape changes in the future with a simple modification of your type you can now ensure that not a single part of your code base references a node which no longer exists without erroring before building.

It has solved more errors on a refactor than I can count - On any large application if you want to have any confidence modifying code it's worth the overhead :)

I'm not arguing against your use case, I'm sure TS helped there, but that can also be done using pure JS. With the proper test cases and JSON schemas put in place (I'm making the assumption you're talking about a JSON-based API), the same thing can be achieved.

Again, not arguing against your use case, I'm just trying to find one that is clearly easier to implement in TS than in vanilla JS.

My 2c:

TypeScript makes your IDE smarter, though you have to do the type definition work. Ever worked with objects with many properties (especially nested properties) and forgotten something? Or have to keep on referring back to some file where it was first defined? Or accidentally slapped on extra properties that should have been somewhere else? TypeScript won't fix the world, but it does help you to avoid these errors and I find that the intellisense improvements speed me up greatly. Functions don't just accept or return arbitrary objects: I can easily refer to structure definitions in code I haven't seen before and get good autocompletion.

Yes, you could also achieve some of this with jsdoc, but if you're writing jsdoc, you might as well define types. It will actually be quicker 🙂

TypeScript is also, imo, the easiest way to get modern syntax like async/await and import syntax. I've found it easier to set up than Babel.

All JavaScript is TypeScript, so you don't have to go "full-on" - adopt what works as you decide to. You can introduce it to an existing JavaScript codebase without having to change your existing code - it can deal with .js files and if you decide to convert some existing code, change to .ts and deal with any warnings/errors. You can also relax the compiler, but I've found most usefulness with stricter settings (like not allowing 'any') and projects where things get the murkiest have been where people avoid the typing system. My advice is to rather try to find / define the correct types than telling the compiler not to bother.

 

Well, I guess I've been neglecting my TS. I'll have to give it a try and see if types and me agree with each other :) Thanks for the nice reply and explanation!

 

It has nothing to OOP. Type systems exists also in functional languages like Haskell Elm or OCaml. I can only agree that type definitions looks similar to these in OOP languages. But it doesn't mean you need to do OOP, even such functional lib like Ramda has type definitions.

 

Agreed, If I where to say that classes (singletons) could be used in a functional programming, I would be branded a Heretic, but a class is just a data structure, it's so tied to the OOP identity, that is all. FP in my eyes, is not about functions at all, it's about expressions over statements and immutability more than anything. Optional typing is a language feature too and nothing to do with FP or OOP. I wish FP and OOP would just get a room and make a little FPOOP 🤯

If I were to say that classes could be used in functional programming, I would be branded a heretic

No you wouldn’t, OOP and FP are orthogonal and a language can exist as both. F# is a good example of this, it has classes and even inheritance but I don’t think anyone would argue that it isn’t a functional language. FP isn’t even about immutability, OCaml, for example, has mutability (and also OO-like objects).

I wish FP and OOP would get a room

The term you’re looking for is object-functional programming; although it is slightly fringe.

😆 the more you know, thanks Andy I have learned something today.

It's an incredibly common misconception; I thought the two were incompatible for years too.

It does get discussed often as if the two things where oil and water. F# is one of the mid sized language I am still to research, but you have given me a reason.

I think this is mostly a consequence of two things:

1) Almost universally, you learn only OOP in school / bootcamps / self-learning. You have to actively search out education on FP, which means that when you inevitably do come across it after years of writing OOP it can seem so alien as to be completely incompatible with what you know.

2) When most people think of FP they think of Haskell which:

  • Is statically typed
  • Is immutable
  • Doesn't have objects at all

Haskell being the poster child of FP has lead to a somewhat inaccurate representation of the field. Many people assume all FP is Pure (immutability, no side effects, referential transparency), when the reality is many functional languages describe themselves as pragmatic; allowing for controlled mutability, side effects, etc...

To bring this discussion back round to the original conversation. Modern javascript is getting very functional: we've always had first-class functions, but now with methods like map, reduce, and arrow functions we can write our code in a very functional style.

Typescript, on the other hand undoubtedly favours an OO style. You can still write functional code, but it's a bit more hassle and you'll often find yourself reaching for features found in other typed functional languages that just don't exist in ts / js.

In Elm, for example, there is a Result type that models a computation that can fail. It looks like this:

type Result e a
  = Ok a
  | Err e

it looks like you can achieve this in typescript all the same:

type Result<E, A>
  = Ok<A>
  | Err<E>

But if you know ts you know that this is invalid. In the Elm version Ok and Err are constructors for the type Result. In typescript, Ok and Err are types themselves, and so we need to go ahead and actually define them.

I could continue, but this reply is getting too long and I'm sure you (and others) get my point. Even fully typing a curried function becomes a jumbled mess:

const add = (a: number): ((b: number) => number) => (b: number): number => a + b

My opinion stems for a video of functional c++ of all things. Anyway take this reply and make a post this is interesting!

 

I agree. Typescript is unnecessary and it speaks more to the inexperience of the developer using javascript than enforcing good practice. I am a huge proponent of TDD (Test Driven Development), which innately forces the developer to gain a more in depth understanding of javascript and functional programming.

 

I have been programming for decades and most of that time has been in 100% in JavaScript. I prefer TypeScript and have used it exclusively on the backend and front end for 3 years now.

speaks more to the inexperience of the developer

So if I am an experienced developer and tech lead... maybe... just maybe there is a reason why I’ve chosen TypeScript. Use the best tool for the job.

Additionally, I only write in a functional style. TypeScript has never impaired my ability to write FP. Map reduce for life. Btw, ImmutableJS and Ramda have great type definitions. And as someone above said: Haskell has types. So... what’s your response to that?

The biggest problem of typescript that it is not sound. It forces you to always write complex type calculations. For FP it is very essential. When I used reasonml I was focused on writing the code. Flow also fits much better because of the same reason. Try to add types to a reduce function or to transducers. Typescript is not strict even in the strictest mode. Type casting to unknown to whatever or adding exclamation marks to the code. React works much better with Flow than with typescript. After switching to typescript I feel more like types developer.

 

For me you can't tell it's better way to write JavScript code and tell people to use TypeScript.
You're not talking about JavaScript anymore.
as

deleteman123 image


says it would be better to get them to actually understand JS's paradigm instead.
 

Recent TS release notes have admitted the oop paradime and are looking at changing the docs to fit FP which typescript is certainly capable of doing. It's just poor marketing.

 

Great list, Ryland 👍

I would like to add json-server, it's a freaking awesome tool to let the frontend developer work on his own.

The big plus is that it auto-magically makes the developer be able to write cleaner code (knowing that he will switch the backend api service later).

 

Hey, that looks like a very cool tool. It's like nock but for everything that isn't testing.

The big plus is that it auto-magically makes the developer be able to write cleaner code (knowing that he will switch the backend api service later).

That's always a great plus. Will have to try it out later. Thanks for recommendation. Glad you enjoyed the post!

 

Just checked out JSON server it looks really cool, Thanks

 

While a lot of your advice is nice, about map and friends:

This directly communicates to the runtime, that the individual "iterations" have no connection or dependence to each other, allowing them to run concurrently.

No JS engine does this. JS doesn't magically run in parallel—it's a single-threaded language.

edit—I was a bit mean before. I blame lack of sleep.

 

From the article:

JS is single threaded, but not single-file (as in lines at school). Even though it isn't parallel, it's still concurrent. Sending an HTTP request may take seconds or even minutes, if JS stopped executing code until a response came back from the request, the language would be unusable.

I think you might have missed a couple paragraphs. In case this doesn't make sense, read my article about async, concurrency and parallelism.

 

Your article writes that map is a construct that JS provides us that runs tasks in parallel.

But map doesn't care if you're passing it an async function or not—it runs a function on everything you pass it, in order. Notably, even this is possible, because async functions don't yield unless you actually call await:

const x = [1,2,3,4,5];

let expectedValue = 1;

x.map(async (value) => {
  if (value !== expectedValue) {
    console.info('actual', value, 'expected', expected);
  }
  expectedValue++;
});

At some level you're right that map isn't an inherently parallel construct. But I still stand by what I said, map has the potential of being parallelized on a level that a traditional for-loop does not. A for-loop explicitly surfaces a mechanism to enforce ordering, a map (and forEach) do not.

In your example, the code is not guaranteed to have a consistent result. The only way it could be consistent is if V8 guaranteed in-order execution of asynchronous tasks, which it does not.

Another differentiator in my mind is state. Anyone who has worked with distributed systems, knows that shared state is incredibly expensive. A traditional for-loop inherently provides shared state, the iterator/bounds check variable i. This inherently orders the loop, while map may be implemented as ordered, it's an implementation detail. Original MapReduce wasn't ordered.

I would say the moment you slap await in there, the code is no longer asynchronous. It's blocking as any other line.

That’s not true. If I await a web request in some random function, it will still be asynchronous as long as the random function is invoked asynchronously.

Try doing two awaits in a row and check if they run concurrently. This is the definition of synchronous.

 

Aside from the overhead of adding types to your code, there are zero downsides to type-safety enforcement.

Au contrarire, the downsides of type-safety are too many compared to any benefits TS may have:

  1. Makes your code more verbose and unreadable due to various type declarations.
  2. Makes your code less expressive and more rigid.
  3. Not a W3C standard, imposed by a single corporation (Microsoft).

The Buddha's way is to face your maladies directly instead of creating abstractions around them. I'd rather write my code in ES6 than write TS and then convert to ES6!

 

Makes your code more verbose and unreadable due to various type declarations.

Incredibly subjective.

Makes your code less expressive and more rigid.

I'm actually not sure how a typing system could make code "less expressive". Can you provide an example?

Not a W3C standard, imposed by a single corporation (Microsoft).

The language is open source, the spec of the language is open web. This statement entirely misrepresents TypeScript. Would you tell people not to use Java because it was created by Sun (now Oracle)? What about C#? What about JavaScript, a current trademark of Oracle?

The Buddha's way is to face your maladies directly instead of creating abstractions around them. I'd rather write my code in ES6 than write TS and then convert to ES6!

Au contrarire, you should be writing V8 bytecode. Or maybe even just skip all abstractions and send 1's and 0's via electrical current.

:)

 

I disagree on this point.

“The Buddha's way is to face your maladies directly instead of creating abstractions around them.”

The Buddha would want you to “communicate mindfully” and to speak clearly. Types clarify reality which is what Buddhism teaches to respect:

 

Great article and a nice overview that can inspire a lot of people. I'm also a big fan of using TS, it's still JS just a little safer.

I do want to correct you on the topic of web automation that selenium is not the only free option to do so.
I think Cypress is very good free alternative. They do have payed (hosted) options but aren't mandatory to use.
Besides that, it has a low learning curve and excellent documentation.
Not to mention the very good tooling to write, debug and run tests fast.

I do want to note that because of how Cypress and Selenium approach a web application, one or the other might not be suited for every situation.

But, Cypress is certainly worth mentioning ;)

 

It's funny because my engineering team at work is trying to pitch me Cypress right now too. For a long time, I didn't like Cypress because it only worked with Chrome. I've hear that they've changed this, which would definitely shift my perspective on it.

Cypress also is nice because of the way it integrates with CircleCI. Thanks for the insightful addition, I probably should have mentioned Cypress.

 

Try TestCafe then. AFAIK Cypress is not free. TestCafe is free and works in multiple browsers, even remote, mobile, headless or not.

 

Solid tools and advice. Out of curiosity what is your opposition/alternative to using null? Sometimes it is a bit unavoidable depending on the backend/backend team you are working with and can also help to show intent that something is purposefully w/out a value.

 

I'm curious as to when you would want to explicitly pass/accept an argument that has no value within JS... Most programmatic behavior happens within arrays (hence the large drive for people to now grasp map, filter, and reduce) and on objects/hashes/maps/whatev your language calls them. In the case of the array, a null or undefined is most likely something you're only going to care about skipping over so your program doesn't crash. And in the case of the object, why look to operate on a parameter that you don't expect to be set?

Especially when it comes to forEach, map, and reduce, the better option than null is usually a default, blankish value, like 0 for addition/subtraction, 1 for multiplication/division, "" when you expect to be working with strings, [] for when you expect to be processing a list, and {} when you're expecting an object. As an added bonus, while they aren't technically able to prevent type bugs, using defaults in function signatures can hint to other developers what the types of their arguments should be.

function convolutedExample(numbers = []) { 
  // maybe something using an object would've been less convoluted...
  return numbers.reduce(((product, factor = 1) => product * factor), 1)
}

convolutedExample([1, 3, undefined, 4]); // returns 12
convolutedExample();                     // doesn't crash
 

This is a very very good reply.

Most programmatic behavior happens within arrays (hence the large drive for people to now grasp map, filter, and reduce) and on objects/hashes/maps/whatev your language calls them

Is especially accurate. It's not that I think null can't be used well, I just don't understand why it fits in a incredibly high-level language like JS. Great comment.

 

One of the best things I've done for writing better JS was to really understand the native array methods like map, reduce, filter, etc.

So much of what we do as developers is the manipulation and processing of data, and if you can learn how to do that in a declarative rather than imperative way your life is going to be so much better.

 

Couldn’t agree more. One path scales the other doesn’t.

 

I'm with you on most of this, but I've found code that borders on illegible because of overuse of the spread operator. Especially when dealing with React state, doing an Object.assign is sometimes a lot easier to read than many lines of ...nextObj,.

As always, tend towards readability. The computer does not care what your code looks like, but other devs will.

 

Don't even get me started on the spread operator visual design. I think the fact that they didn't come up with a specific syntax and used the existing rest style is atrocious. They actually do opposite things, and are somehow controlled with the same literal. This is just off the top of my head. But why not:

function (...foo) { // before
  foo[0];
}

function (_>foo) { // after
  foo[0];
}
expanded = ...foo; // before
expanded = <_foo; // after
 

I've been around a while, so I'm comfortable with the for-loop. I often use other tools, but there are times a for-loop fits the task.

I was not aware that they are highly inefficient constructs that prevent parallel tasks from executing. I'd assumed that other methods for iteration like map or forEach were convenience methods that looped over records under the hood using a for-loop. Apparently not so. I need to do some more research.

 

TS types are really bad, you should need to do stuff like:

let foo: number = 42
if (foo > 100) {
  throw_error_too_big();
};
if (foo < 0) {
  throw_error_too_small();
};
// Actually use foo

This Nim lang instead only takes integer from 0 to 100:

let foo: range[0..100] = 42

🤔

 

I’m sorry but this is a really weak argument for Typescript having a bad type system. This is already a feature that is planned for TS too.

Also your code is not optimal TS and could be condensed to a single line.

 

FPOOP it's a new design pattern I just invented and looks like Typescript can already help me write some FPOOP.
FPOOP consists of two paradigms FP and OOP, the main rule is to choose the appropriate paradigm for the job, FPOOP.

 
 

I’ve been practicing “functional code imperative shell” for a while (and in TypeScript might I add!).

 

Maybe I'm a dinosaur, but I don't always find arrow functions nor destructuring to be more readable/understandable.

This:

function animalParty(dogSound, catSound) {}

const myDict = {
  dog: 'woof',
  cat: 'meow',
};

animalParty(myDict.dog, myDict.cat);

Is easily the more readable solution vs:

function animalParty(dogSound, catSound) {}

const myDict = {
  dog: 'woof',
  cat: 'meow',
};

const { dog, cat } = myDict;
animalParty(dog, cat);

With the former, you can also get more info about the variable just from how it's used.

dog allows you to access the value of the myDict property, yes. But myDict.dog not only allows a developer to access the value, but it also allows for the dev to know immediately that the variable is a property of an object, which can give a clue on where to look to get more insight into the larger object itself.

 

Bloody solid read as always mate!

I was itchy to not do TS for a long time coming from a pythony background.

But I've unfortunately learnt the importance of strongly typed languages.

Overall was awesome too!

 

Glad you liked it. TypeScript was a hard sell for me not too long ago. Definitely was worth the startup cost. Thanks for sharing.

 

"The number one thing you can do to improve your JS, is by not writing JS"

Kind of a joy-killing way to start a JS' best practices article... :/
I like TS, but it definitely does not belong in all JS contexts.

 

I'd be interested to hear why you think null shouldn't be used often, and what you would suggest using instead? I use it all the time and can't think of anything that fits better for the concept of "nothing". I can't think of any times when I've used it and been bitten by it either, and in fact I think it's a more solid way of coding than the other ways I've gone with over the years, for example "undefined" can be confused with a property not being present at all, false is no use if the value is supposed to be either boolean or nothing, similar problem with the other falsy values - whereas going for the something === null check is always going to work, and is nice and explicit.

 

you can even leave the () when writing one-parameter-arrowfunctions:
for example, you used:
const resultingPromises = urls.map((url) => makHttpRequest(url));
this can be written as
const resultingPromises = urls.map(url => makHttpRequest(url));

 

I think that this portion is a bit disingenuous "Before TS, other solutions to this problem existed, but none solved it natively, and without making you do extra work."

TS is not native and not without extra work.

I'm fine with transpiling ES6 to ES5 if you have to support older browsers because it's still standardized javascript and as a full-stack developer you'll be writing server-side code in ES6 and will instinctively continue to write it for js destined for the client... Why force the context switch if a workflow can sort that out.

I'm less OK with using some vendor's interpretation of how the language should be even if there's potentially some benefit to it. The fact that it's not a part of vanilla Javascript is why there's scala.js, st-js, and js++ in addition to typescript...

I do recognize the same argument could be levied against my use of SASS. The distinction -- in my mind -- is that if SASS fails to compile the page still renders (poorly, but the content is still available), the app will start, etc. If javascript fails to transpile it won't run and I can't abide that.

I agree with everything else I read, though I might advocate nightwatch or puppeteer over selenium proper.

 

While I use NodeJS for prototyping apps and this is the use case which I see node used for widely, I would pick a statically typed language if I ever needed all of this (Instead of something that transpiles to JS).

TS takes longer time to dev (which is shorter for JS) without any added performance benefits. I dislike it for this reason.

 
 

Hey. Thanks for this article. well explained, and a good reminder :)
I've also started working only with TS now, and I really like it even though sometimes I still find it a bit difficult to define interfaces and types.

Also another really important thing with ES6 is all the array manipulation made possible with reduce, map, filter, etc. Not always easy, but a MUST know I would say !

 

Great article.

Could you link to an article or explain "Numbers in JavaScript just suck, always use a radix parameter with parseInt" further?

I understand magic numbers aren't ideal but what exactly makes a radix parameter superior?

 

Use ClojureScript/Reagent/React/Re-frame and stop setting your hair on fire with any kind of JS construct...😬
Lint ... 🙄 I was using lint in the 80s... c'mon, we are in 2019 and still using 30 years old tools ? 🤪👈🔨

 

Just a tiny check in code, I think you wanted to say myArray.length instead of

for (let i = 0; i < myArray; i += 1)

Good article Ryland!

 
 

Hahaha, the conclusion is epic 😂. This article is brilliant. I'm motivated to give Typescript a try after reading this. Thanks a lot for sharing.

 
 
 

Practical Ways to Write Better JavaScript
.
.
Use TypeScript! LOL

code of conduct - report abuse