How I improve my JavaScript everyday

Tram Ho

Which Editor to use?

Currently for programming, there are countless types of editors out there that we have just learned to stun, don’t know which code to use for productivity.

With me except for Android code required to use Android Studio or iOS using Xcode, I mostly only use Visual Studio Code .

This is an editor developed by Microsoft. It sounds good to hear from Microsoft, your products must be genuine. And yes it is genuine, supports almost all languages, countless additional plugins for everyone, there is AI code suggestion, beautiful interface, and nhẹ (I feel not much heavier than you guys). same age group)

VSCode

In the past, there was a time when I only used Sublime Text (VSCode was not popular at that time), my friends told me to switch to VSCode but it was really wonderful to be conservative and not until it was transferred. Combine with the plugins (which I will talk below), automatically detect and fix errors, format the code yourself. I save a lot of time when I no longer need to fix small errors that are common when coding.

If you have PHP code, you will like PHPStorm, Python code will like PyCharm, it’s true that those editors are strong but only for one language, and I am Fullstack Javascript, HTML, PHP, NodeJS and React Docker, … then I use VSCode because it is extremely powerful, support a lot, the most favorite is the very intelligent autocomplete ❤️

Love ESLint from today

One of the things that makes me spend the most time and frustrating is syntax errors, errors that don’t declare variables / functions that I use, missing accents, … When our code gets bigger, those eyes Tired of having to read dozens of files at a time, mind reeling, hands trembling typing each line of code ? , leading to our being overlooked and making mistakes.

When I use an ESLint code, this is a plugin that helps find errors, check syntax, format code, thereby reducing bugs when coding, and helping the code look better when formatted according to popular standards in the world. . ESLint supports many big brothers: pure Javascript, React, Vue, …

Especially using ESLint with VSCode, that’s all, ? , perfect couple, type the code to where will be checked for errors / syntax immediately and suggestions on how to use functions and variables for optimal always. There is also auto format code again, just listen and feel loved ❤️ .

ESLINT_VSCODE

Actually, from the day of using ESLint, I have reduced most of the small errors that are extremely common, in the past, it used to be that the code -> build -> ran missing a variable report, corrected -> build -> ran and reported missing 1 function, extremely inhibited. But I’ve been Say Goodbye long ago with those things ? , code is much more productive

Besides ESLint, there is also Prettier also used to format the code, but I prefer ESLint because it supports error detection and code suggestions for optimal.

The optimal directory structure

One of the things that I recently came to “accept” and told myself was like the heart essence:

Do not try to optimize the project structure from the beginning of the project

If the project structure is good or not, then the project will become broken later? ?

In the past (not really before, just a few months ago), every time I started a project, no matter how big or small, I always spent a lot of time trying to choose a project structure that was optimal, go online and read all kinds of “NodeJS folder structure best pratices”, … but then you still wonder whether this is optimal or not, should you choose a framework to code, bla and blo, very time-consuming. .

And I also realized that even though at first I tried to follow a structure that was supposed to be good, a few days later, my code turned into a mess. ? Because my system thinking is not good, initially how beautiful the code structure looks at once ? .

Do not think too much about what architecture to choose, how to organize it from the beginning. Choose a direction or a library, framework and start working on it, doing it while improving so that it is good and practical.

This part says so little for the next sections ?

But if any of you are interested in a well-structured project, I share with you a NodeJS framework called NestJS , I read a lot about their docs and found how their architecture is very good (quite similar to AngularJS, although Although I don’t like Angular much ? )

Console.log anywhere there is a “smell”

When JavaScript code is sure console.log is what I use most. The main purpose of this is to see if the data at the position you are interested in is actually true or not.

Many of you ask me if this code is not working, why the data is not correct, I ask if you have console.log yet, tell where the console is, where it looks, the console does not see anything, until I say When you take a screenshot of the console tab in Chrome, it will appear red ??

I personally think that programming, regardless of the language, mostly revolves around data, so if you see any code that is disturbing, maybe not right, you should console.log to make sure .

There are also many who say that a debugger looks more professional and programmed, and Chrome also supports placing Debug in lines of code that will know better. In fact, this is not necessary for me personally, console.log also notice in which line in the code, and use console.log faster, more convenient, but I saw the tutorial of the world famous code Google Facebook You still use console.log ?

But you should also note that when console.log finished, check everything is fine, then delete it, do not put the whole console.log code on git or show it to others (as shown below), yes they will be very inhibited and sore eyes (like me for example) ? , stop teasing that, I’m so cute, if you have any questions, please send me your code ?? )

console.log

Comment on time

In the process of code, there will be many times when we have long, complicated code, we are afraid that when we read it again, we will not know what this code does anymore, or with a humanitarian heart, we want people who come after to read the code can understand what it does.

Personally, I find it really useful to write comments, especially when the project has many people working on it and not always do not understand that we ping the friend who wrote the code, while that friend also is compensating early 1 ton of bug early morning testers sent over ? , then if the comment code is explained, the following people can understand immediately and save time.

But the comment must also be reasonable and cute ? . There is no need to comment on everything, and comment on the level of your teeth, which will sometimes make your code difficult to read and make others suffer from eye pain. ?

bad_comment

When writing regular code, I will choose the name of the variable / function so that it is easy to understand, do not let a long class / function handle too much, instead I split into smaller classes / functions (but do not peel too much. Many of you, it must be reasonable not to develop eye pain ? ). And just comment when you feel it is necessary, practice writing code so that it is “self-explain”, read it and know what it does.

In the example above I can write down as follows, others can also understand what this function does, which parameters to take, reduce lengthy comments:

Use ES6,7,8,9 standards

Javascript is a very fast growing language along with the addition of many powerful built-in functions / libraries. As far as I know, every year “people” publish Javascript standards called ECMAScript or ES for short, each of them includes a set of a series of new features integrated into Javascript.

YearStandard
2015ECMAScript 6 (ES6)
2016ECMAScript 7 (ES7)
2017ECMAScript 8 (ES8)
2018ECMAScript 9 (ES9)
2019ECMAScript 10 (ES10)
2020Probably still ?

So, if the code, if we take advantage of the power of the upper hand of javascript, our code will look much better, optimized and look much cuter than just using the traditional for and if , while ? (cute as you write this article ?? )

Below I have a few examples of functions / operators I use most when coding:

There are also a lot of new things that are updated every time a Javascript standard is published. Using them in a flexible way makes our code much cleaner and easier to understand ?

Skip Promise / Callback and switch to Async / Await today

The imprisonment of the Promise / callback

This part I completely separated into an item that is not included with the above standard section because I see there are still many of you are familiar with Promise / callback, sometimes you send me the code to see that stunned right from the notes first music ? . And the thing is this is …

While code, we almost certainly have to work with the API a lot, call the API from the backend or from the third party to get data and display it. Usually we will do the following:

And if you want to call another API only after successfully retrieving the user list, you will often do the following:

The bad thing to knock is when we want to call a series of APIs in order. And this is exactly what you saw when the project scale got bigger and the requests processed were more and more complicated ?? :

Promise_hell

The same thing will happen to you or use the callback function (where to run for all the sun ? ). Your code will look extremely confusing because of the nested processing instructions, which will later cause you to re-read and be immediately summoned. ? , it’s for you who write the code, and for the latter, it really faints at first sight. ??

Async / await to save the world

Since ES6 (2015), async/await been introduced as an alternative to Promise / callback in handling asynchronous operations. The great thing about async/await is that it helps us write asynchronous code that looks like synchronization, the code runs line by line, looks very nice, neat.

For example, the above code takes a list of users and addresses we can rewrite using async/await as follows:

Sorry, the code looks neat, right? ? . The code looks asynchronous, making sure to run sequentially as we like.

Above the API calls like axios.get('/users') or axios.get('/addresses') returns us a Promise (asynchronous handling that results are not immediately returned. (at some point later), when we wait await before Promise, the code that runs to that line will wait until the Promise returns our value (or error when timeout). Thus asynchronous requests are handled in a simpler, more intuitive way.

The same thing must be done when there are more asynchronous processing, we just have to waitit them all. ?

But there are a few things to keep in mind:

  • await always comes with async
  • Use try/catch to catch error handling operations inside async function
  • The nature of await is that it will wait until the Promise returns the value, so sometimes await too much will make our app slow.

I lost some time because I was afraid to change to a new one but until now, I rarely come back to Promise anymore. ? .

Well, there is another nice thing about using async/await instead of the usual Promise / Callback, that is when using try/catch to try/catch async/await errors and also allows us to catch all the other errors inside. that try/catch block, not just async/await anymore. Take a quick look at the example to understand it ? :

The above example is a simple case where try/catch helps us catch errors. Imagine a long piece of code like an international passage when using Promise when an error occurs ?? , but when using try/catch , we can catch all the errors occurred in the try/catch block. See you yet ❤️❤️

  • “But now does the code always have Promises and callbacks like this passing to async / await?”
  • “My code is so confusing, are you sure you can switch from Promise / callback to async / await”.

So the answer for you is: you can always switch from traditional asynchronous forms (Promise, Callback, or asynchronous event emitter types) to async/await . ?

Here I list some of the cases I often encounter when needing to switch from Promise, callback … to async/await

It also looks like it doesn’t take long to switch to async/await right? ? , It is important that our code is beautiful, easy to maintain, and later on to make sure the eyes are not sick anymore ?? . In general, as long as you convert the asynchronous Promise, callback hay dạng event into Promise , we can await (of course, if the Promise is already available, there is no need to say much, always async/await ). good brothers ? )

Note: nothing in life is perfect, neither async/await ? , there will be cases where we still have to use Promise / callback. But in general, I personally find that async / await solves a lot of problems, more is what is lost ?

Improve code quality with Typescript

The story begins …

When I first started programming, I started with C, then Java, they are languages ​​that I find quite strong, and require extremely strict code. Requires clear and full definition of data types (string, boolean, …) or access specifications (public, private, protected, …), I sometimes feel tired of running The code does not know whether this is public or private, does not know what its data type is, just run when the error is reported ??

After this move to Javascript (or PHP, Python), it has been greatly simplified because no matter what the data type is. Just declare the variable is always done:

This is also one of the things that made me love JS from the beginning because the syntax is very “liberal”, less messy, looks clean and beautiful code. ? . And life is not like a dream, no love is forever pink ? , gradually I realized that when the project has many people, or after code 1 time we come back to read the code, we are really confused by not knowing what this variable is, how this function returns .. .

And it is almost inevitable that I will have to do the following:

This takes me a lot of time, and it is unlikely that I will come back to read in the future, or new readers of code I can understand, and I / they have to do a few dozen console.log commands to understand. What does the code do? ?

Typescript solves a sore problem

Read blogs, tutorials on Medium, Hackernoon, wandering on Google I know Typescript .

Typescript, in my opinion, is a plain JavaScript “upgraded version”. Now our JavaScript code will have clearly defined types (string, boolean, number, …), accessible access functions (public, private), … and many other things. Code written in Typescript will be compiled into plain JavaScript, so we can run as usual, no need for specialized Typescript scripts or anything else. Check out some examples ? :

Thanks to writing JavaScript code but “having type”, so our code will be much tighter, when reading, we can understand what this variable is data type, this function takes input parameters, returns how is the data?

WTH? Are you kidding me? I went from C -> Java -> … -> to Javascript, going all the way, ? , pure Javascript code is so beautiful, he added some bla blo data type, now it looks messy? Is there any difference between Java and C ++ code? So it turned out that I was returning to code the way I used to? The above sections are about eye pain, here my eyes are about to fade here and here. ??

The code is wordy, leave it alone, I can use console.log.

For me, I heard about Typescript about 2 years ago, but I still don’t like to use it and I don’t want to use it because I just love the openness of Javascript, sometimes I want to try it but my eyesight is sensitive, I feel so confused. is an eye disease it develops ??

But a while ago I decided to switch to Typescript because of the headache issues I mentioned when I read the old or other people’s code, and also because the dev community tends to switch to Typescript a lot and Very good review. And yes, although it was a bit difficult at first, later I found Typescript very easy to use, because it was just like “upgrading” of Javascript, code moving from Javascript to Typescript is very easy, even if any Javascript is not want to move to that ? .

Now every time I return to read the code, I can immediately understand and understand what each variable belongs to, what type this function returns, whether this array has been changed throughout the program, … a lot of time and minimize redundancy to check data (I mean use console.log to check that you ?? )

Currently I see Typescript is a trend of Javascript dev brothers, new libraries, new frameworks almost pay attention to support for Typescript like Angular, React or Vue can write Typescript. For you who do not know: Vue 3 is 100% Typescript rewrite always you ? . Also Typescript is developed by Microsoft, so you are assured of the quality and support ?

In the past, when I read about recruiting foreign jobs, I always demanded Typescript / Flow *, and kept seeing that type of job, I was running away because I did not know what Typescript / Flow was all about, but the title was about do web that, why not use every mark Javascript is also that ??

* Flow is also a kind of almost Typescript developed by Facebook, React / React Native code people also use quite a lot

But now it is also called “familiar” to be Typescript so there is no more fear of those types of jobs (the number of jobs increases rapidly), and it’s true that when the project scale is bigger, more people then we will see its convenience. Although the current project I’m working on does not have many people, I have almost turned the whole Javascript code into Typescript. You must also practice preparing to improve gradually, learning the better things for a bright future, my good brothers. ?

CI / CD – Code -> Test-> Deploy

In this section, you guys have read the title, “I’m going to sleep,” but I hope you can read it because I see this trend in recent years.

Automation test

Actually, this is a problem that everyone knows, but many people still ignore and try to focus on the code for really loud. ?

I just want to tell you a little bit and then proceed to the following:

  • Sometimes too focused on code but forget the test so when deploying code has many errors, lightweight, quick fix, deploy is completed, heavy leads to data errors, incorrect system processing, …
  • And also sometimes we think that our code has covered (completely covered) the error cases so we are subjectively not testing anymore leading to the above result.
  • And then again because of subjectivity, having tests, but not careful testing led to almost fighting life and death with Team Tester for “doing my code so many errors, I test it all”. ??

So from now on, we should practice the habit of writing tests after we have completed one / several stages in the development process, carefully testing to cover most of the basic cases. Every time before committing, run the test to let it test the code for us, then push the code, but the test is fully automated, I only need to define one time. ?

CI / CD – Test and deploy continuously

CI / CD (Continuous integration / continuous integration), I think this is a trend now, a new way to help us write code, test and deploy automatically and continuously. CI_CD Previously when the code was finished, we need to test then if everything is ok, then commit the code to the repository, even though the local has already been setup automation testing, run a check code ok and then commit is completed.

  • But what if a person who hasn’t tested the code pushes to the public repo right away? then there will need to be people who go to review code, check the code again to make sure everything is okay
  • If the local accidentally deleted some test cases in a “unconscious” way ?? , still run the normal test, through the rigorous testing steps, the commit code is finished and oh well when the tester jumped in, the Chrome console turned red ??
  • Especially for projects with many people involved, or like libraries / frameworks with hundreds / thousands of contributor, can not trust the testing skills of the dev father, he will test all the miscellaneous commit code If you have an error, you should not review the code ??

So tools for automated test code, build code and deploy are born. These tools are usually set up with the repository with no source code, we set up test scripts, build project steps, then deploy, then with every dev commit will be automatically checked through the steps / scripts. That, if ok, then merge into the main code, then build and deploy to run. This process is called CI / CD.

This saves a lot of time, minimizes redundancy and repetition, and allows us to deploy code to production as soon as possible.

Ok got it, how to start it:

  • First you should learn more about Docker
  • Write automation tests for the project (of course, there must be tests ?? )
  • Find platforms that offer CI / CD services. Here I often use Gitlab, because Gitlab is free, private and has a lot of powerful tools for CI / CD compared to other places (according to my view through circleci and travisci, the evaluation is so fast ? )
  • Learn and configure tests (unit test, api test, coverage test, …), build deploy automatically.

Epilogue

Phew, as usual, this blog was lengthy like other articles, yawning and yawning. ??

Through this article, I hope that I can convey something from what I have learned to help you to improve your JavaScript coding skills, improve your ability, thereby opening up opportunities. New, create more quality products ?

Javascript I see is a language with fast development speed, extremely powerful (build most types of applications on all platforms that I know), so if you keep updating, learning, updating. Update can help us shorten development time, improve productivity and quality and help us reduce sore eyes even more. ??

Thank you for following my blog, if there is anything incorrect or if you have something interesting, please comment below for everyone to know. ❤️❤️ .

Share the news now

Source : Viblo