DEV Community

Cover image for Practical Ways to Write Better JavaScript

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. ...
Collapse
 
deleteman123 profile image
Fernando Doglio

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.

Collapse
 
taillogs profile image
Ryland G

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.

Collapse
 
mazentouati profile image
Mazen Touati

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

Thread Thread
 
taillogs profile image
Ryland G

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

Thread Thread
 
mazentouati profile image
Mazen Touati • Edited

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.

Thread Thread
 
ms_35 profile image
ms

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

Collapse
 
yaser profile image
Yaser Al-Najjar • Edited

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

Collapse
 
taillogs profile image
Ryland G

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!

Collapse
 
itsjzt profile image
Saurabh Sharma • Edited

Just checked out JSON server it looks really cool, Thanks

Collapse
 
samthor profile image
Sam Thorogood • Edited

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.

Collapse
 
taillogs profile image
Ryland G

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.

Collapse
 
samthor profile image
Sam Thorogood

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++;
});
Thread Thread
 
taillogs profile image
Ryland G • Edited

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.

Thread Thread
 
pavelloz profile image
Paweł Kowalski

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

Thread Thread
 
taillogs profile image
Ryland G

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.

Collapse
 
prahladyeri profile image
Prahlad Yeri • Edited

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!

Collapse
 
taillogs profile image
Ryland G • Edited

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.

:)

Collapse
 
cubiclebuddha profile image
Cubicle Buddha • Edited

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:

Collapse
 
gingerrific profile image
Josh Date

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.

Collapse
 
thepeoplesbourgeois profile image
Josh

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
Collapse
 
taillogs profile image
Ryland G

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.

Collapse
 
ineth profile image
Thomas DP

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 ;)

Collapse
 
taillogs profile image
Ryland G

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.

Collapse
 
pavelloz profile image
Paweł Kowalski • Edited

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

Collapse
 
cookavich profile image
Paul Cook

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.

Collapse
 
taillogs profile image
Ryland G

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

Collapse
 
ballpointcarrot profile image
Christopher Kruse

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.

Collapse
 
taillogs profile image
Ryland G • Edited

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
Collapse
 
adam_cyclones profile image
Adam Crockett 🌀

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.

Collapse
 
taillogs profile image
Ryland G

Also the fp-TS library

Collapse
 
cubiclebuddha profile image
Cubicle Buddha • Edited

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

Collapse
 
juancarlospaco profile image
Juan Carlos

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

🤔

Collapse
 
taillogs profile image
Ryland G

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.

Collapse
 
focus97 profile image
Michael Lee

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.

Collapse
 
harveyramer profile image
Harvey Ramer • Edited

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.

Collapse
 
sebbdk profile image
Sebastian Vargr

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

Collapse
 
rossler123 profile image
Markus Rossler

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));

Collapse
 
veebuv profile image
Vaibhav Namburi

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!

Collapse
 
taillogs profile image
Ryland G

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

Collapse
 
68935679 profile image
Gus

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.

Collapse
 
kikekeys profile image
Enrique Tecayehuatl

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!

Collapse
 
taillogs profile image
Ryland G

Thanks a ton.

Collapse
 
estellechvl profile image
Estelle Chevallier

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 !

Collapse
 
reevebarthelme profile image
ReeveBarthelme

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?

Collapse
 
anirudhr95 profile image
Anirudh Ramesh

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.

Collapse
 
danielpklimuntowski profile image
Daniel Klimuntowski

Thanks. Cheers!

Collapse
 
taillogs profile image
Ryland G

Glad you liked it.

Collapse
 
bradley56700115 profile image
Bradley Thompson

After reading your article, I also thought about using Typescript. The help of ukessay.com/thesis-writing-help for compiling a small abstract on this article would not be in the way. All the same, some of them will definitely help me with the next project. And since writing code is still not easy for me, thesis will obviously come in handy.

Collapse
 
waffledonkey profile image
waffledonkey

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.

Collapse
 
lprefontaine profile image
Luc Préfontaine

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 ? 🤪👈🔨

Collapse
 
sarah_chima profile image
Sarah Chima

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.

Collapse
 
68935679 profile image
Gus

Nothing wrong with null...

Collapse
 
lqj profile image
QJ Li

Also make sure eslint is turned on :)

Collapse
 
bblackwo profile image
Benjamin B

Array.prototype.includes() and String.prototype.includes() are also some great new JavaScript features! :) I hate seeing indexOf('something') >= 0 but people still use it all the time!

Collapse
 
greatgraphicdesign profile image
Alek Vila

In the spread operator example, you make a comparison between old and new ways that makes the old way look cumbersome. You called this clunky:

const obj1 = { dog: 'woof' };
const obj2 = { cat: 'meow' };
const merged = Object.assign({}, obj1, obj2);
console.log(merged) // prints { dog: 'woof', cat: 'meow' }

... But it can also be this, right? An apples-to-apples comparison:

const obj1 = { dog: 'woof' };
const obj2 = { cat: 'meow' };
console.log(Object.assign({}, obj1, obj2));

The above tells me that I'm using the Object assign() method, which makes the code more clear to me. I don't see the case for switching to something as vague as:

const obj1 = { dog: 'woof' };
const obj2 = { cat: 'meow' };
console.log({ ...obj1, ...obj2 });
Collapse
 
geoffreydonahue profile image
Geoffrey Donahue

I spent a long time using Javascript. JS has always been the last one to stand every single moment.

Collapse
 
najuste profile image
Justina Nainyte-Dogdu

It made me smile reading the headline and landing on an article about Typescript: a bold message, but nice points!

Collapse
 
charles66982918 profile image
charles hollins

Thank you for the post. Interesting.

Collapse
 
sibi profile image
sibi

Thanks, Ryland :)

Collapse
 
hassan_dev91 profile image
Hassan

Hi there. this is so nice article for js developers. I like it. I want to ask do you allow me to translate this to my local language?