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.
...
For further actions, you may consider blocking this person and/or reporting abuse
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.
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-...
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.
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
mapand friends: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:
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
mapis 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:At some level you're right that
mapisn't an inherently parallel construct. But I still stand by what I said,maphas the potential of being parallelized on a level that a traditionalfor-loopdoes not. Afor-loopexplicitly surfaces a mechanism to enforce ordering, amap(andforEach) 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-loopinherently 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
awaitin 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.
Au contrarire, the downsides of type-safety are too many compared to any benefits TS may have:
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!
Incredibly subjective.
I'm actually not sure how a typing system could make code "less expressive". Can you provide an example?
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?
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 would want you to “communicate mindfully” and to speak clearly. Types clarify reality which is what Buddhism teaches to respect:
“Communicating your needs” / TypeScript’s value from a Buddhist perspective (part 1)
Cubicle Buddha ・ May 29 ・ 4 min read
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, andreduce) and on objects/hashes/maps/whatev your language calls them. In the case of the array, anullorundefinedis 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, andreduce, the better option thannullis usually a default, blankish value, like0for addition/subtraction,1for 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.This is a very very good reply.
Is especially accurate. It's not that I think
nullcan't be used well, I just don't understand why it fits in a incredibly high-level language like JS. Great comment.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.
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.assignis 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:
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.
Also the fp-TS library
I’ve been practicing “functional code imperative shell” for a while (and in TypeScript might I add!).
TS types are really bad, you should need to do stuff like:
This Nim lang instead only takes integer from 0 to 100:
🤔
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.
Maybe I'm a dinosaur, but I don't always find arrow functions nor destructuring to be more readable/understandable.
This:
Is easily the more readable solution vs:
With the former, you can also get more info about the variable just from how it's used.
dogallows you to access the value of themyDictproperty, yes. ButmyDict.dognot 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.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
maporforEachwere convenience methods that looped over records under the hood using a for-loop. Apparently not so. I need to do some more research."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.
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));
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.
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 === nullcheck is always going to work, and is nice and explicit.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!
Thanks a ton.
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?
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.
Thanks. Cheers!
Glad you liked it.
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.
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.
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 ? 🤪👈🔨
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.
Nothing wrong with null...
Also make sure eslint is turned on :)
Array.prototype.includes()andString.prototype.includes()are also some great new JavaScript features! :) I hate seeingindexOf('something') >= 0but people still use it all the time!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 });I spent a long time using Javascript. JS has always been the last one to stand every single moment.
It made me smile reading the headline and landing on an article about Typescript: a bold message, but nice points!
Thank you for the post. Interesting.
Thanks, Ryland :)
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?