12 incredibly useful techniques in JavaScript

Tram Ho

Foreword …

Walking around the online newspapers on a sunny and windy autumn afternoon, I suddenly came across an article titled “12 Super Useful techniques in JavaScript” … To a learning enthusiast like me, I suddenly I wonder if there is anything interesting, but obviously I also carry javascript code for a long time and have been working on many projects with it, so what else can I learn?

Then I decided to take 5 minutes to test it, and then I suddenly saw so many interesting and clever ways to deal with things that I thought I already knew. Well, that’s it because the article is so good, so today I will continue to “play the role of Google” to translate it for you to read! Maybe you already know, then consider reviewing with me …

Now, let’s go!

1. Create a general function

First of all, let’s imagine that we are trying to develop a generic (shared) function and input a certain number of parameters to be used during execution.

For example, a calculator has N parameters and N operations. You can easily achieve this using the spread operation and reduce functions :

It’s a quick and quick way to create a “pocket computer” that runs on rice with javascript, right?

2. Switch with range of values

When I used Pascal, C, or old Java, I found the inconvenience of Switch when I was unable to use it with a range of values ​​… So I had to nest if...else continuous in some cases. Actually, back then, I was still “young and green”.

Surely many of you have the same situation as me, so now with Javascript, we can completely handle the problem easily and easily as the code below:

The above image also has a clever technique that instead of using a switch for a certain variable, we will switch (true) and the cases will be the conditions we need to check …

Get rid of endless if...else loops! In our code it is now really “clean”!

3. Combine multiple cases in the switch

Yet another switch related technique, this one you probably already know too! Those who do not know, then look in the picture to understand immediately:

So easy! If we want to combine them, we let them next to each other and there is no break in the middle of the cases.

4. Wait for multiple asynchronous functions at the same time as async / await

This technique is advanced because it is related to async / await , and many of you may have a situation where you want to execute many asynchronous functions at the same time and wait for all of them to finish. So the following technique will help you solve that problem:

As you can see, we will wrap the asynchronous tasks that we need to execute into Promises , then there is a generic async / await function called Promise.all to execute all the work of the Promises we create. .. Very simple, right? If you think about it, I immediately believe it!

5. Make a 2-dimensional array in one easy step

Sometimes in the coder’s life, we will sit and sip a cup of coffee thinking that in Javascript, how can we “stretch” a 2-dimensional array into a one-dimensional array now?

Wouldn’t it have to recursively go into each element of the array and get the value out? No need to be complicated, look down at the photo below and be careful not to “gasp” in surprise:

That, with just the spread operation we can “straighten” any 2-dimensional array!

6. Make a multi-dimensional array in just one simple step

Technique 5 seems “cool”, but only run on rice, actually easier, Javascript has provided us a function called flat () to do the job “straightening” already! But also for multiple dimensions, not just 2-way …

Using the flat () method, we can create a new array with all the elements of the sub-array recursively appended to it up to the specified depth. If you do not understand carefully, look at the photo below.

7. Create “pure” object in Javascript

This technique is probably useful to anyone who wants to build a property on his own, because creating a “pure” object means creating an object in which nothing is anything.

Normally, when we create an object, our object will have some default properties and methods added, let’s take a look at the figure below:

As you can see, although we do not declare, the object that we create also has default properties and methods …

So, if one fine day you hate the default convenience of Javascript and want to mold your own object, do as below:

There, easy again!

8. Delete duplicate elements in array with just 1 step

The story of how to quickly delete duplicate elements in an array is the eternal story of any programmer from the Pascal era that was used to take the National HSG exam.

Normally, to do this duplication, it takes at least 2 for rounds with the basic way everyone can think of, but now, with the strong development of ES6 in Javascript, we just need “one shot” as below picture:

And you know what the result will be !!!

9. Write to the console when the page is started and finished loading

This is a bit of a scenario to use but is also a good technique because you will be able to use it to check performance, load times a page more easily …

You can also use the functions console.time('nhãn tên bạn muốn đặt để theo dõi') and console.timeEnd('nhãn tên bạn đã đặt trước đó') to start and end timer for you to track the time doing a certain action. This is not much of you know, because it’s console.log haha

Or better yet:

Btw, personally I still prefer to use addListener rather than override the event function like this ..

10. Print button for the page

Now we can create a button to activate the printer right on the web so quickly that anyone can press without understanding too deeply about the technology … This is short and easy to understand!

11. Round the number

This is also the basic technique that anyone who has worked with numbers in Javascript will know, but it’s also a good one … We can round it down to the nearest integer, round it down or round up. JavaScript provides us with three methods to achieve this through the Math object.

First rounding to the number of decimals we want, to do this we use the toFixed('số phần thập phần cần giữ') of the variable that contains the numeric value we need:

The output is a string that needs to be passed to the parseFloat() function to return a number. Although this may seem slow, the results are always extremely accurate.

Next is rounding to the nearest number, we use Math.round('số cần làm tròn') :

There is also Math.floor() for rounding down and Math.ceil() for rounding up!

Note that rounding is different from truncation, when we use the Math.trunc('số cần cắt bớt') function Math.trunc('số cần cắt bớt') , it simply cuts off the decimal part of the input number. Not rounding!

12. Empty an array

A while ago when I read this technique, I thought that I just need to assign that variable to an empty array to finish, but when I think about it, it doesn’t really match the “Empty an array” …

So here’s a quick way to do that, which is to set the length of the array to zero. That’s it

Conclusion …

So to summarize the dress, I have finished the job of translator and chef “add salt sauce” to the article to help provide you with or review 12 interesting and popular techniques in Javascript. !

We hope you will receive more useful knowledge after spending 5 minutes reading this little article of yourself.

Have a nice day! I sincerely thank you!

Original article: 12 Super Useful techniques in JavaScript

Share the news now

Source : Viblo