[JS tips] JS “tricks” thought not good or not (part 2)

Tram Ho

Hello friends,

After a period of absence, today I continue to return on a cold day. And to continue the JavaScript tips series, today I would like to continue the second part of this series. If you have not read the first part, you should read it immediately, I bet it will be very interesting:

  1. [JS tips] JS “tricks” thought not good or not (part 1)
  2. [JS tips] JS “tricks” thought not good or not (part 2) ==> You’re here!

Now, continue to learn the tips so that we can “control” JS the best gradually. Let’s start!

1. Eliminate duplicate elements in the array

Let’s start with a familiar problem. Looking right at the title, many people will sigh and say, “God, this is so familiar, mom, there are dozens of tricks on the web to do this game!” . Yes, that is. I do not deny that. You can Google now and produce tons of results for this.

But today I want to give you a clearer view of deduplicate arrays in JS.

1.1 With arrays containing elements of type primitives

Yes, this is what most of you know. And obviously there are “a dozen ways” as you said. But in general there are 2 most common ways:

  • Use the Set collection:

Admittedly, this is the simplest and most memorable way. We take advantage of the feature of Set that it will not contain duplicates in it, adding the same element to it will not receive any more (of course, primitives, but Objects are different, they are different). I will discuss this section right below so don’t be anxious.) So, we will do this:

  • Use loop:

In this way, you can optionally use filter , or reduce , or regular forEach , and so on and remove duplicates as you like. In general, you have to browse the array to perform the type action of the duplicate element.

1.2 With an array containing elements of type object

What about an array containing an Object? Can we simply eliminate duplicates like the above? Of course not after we look at a few small lines of this code:

Oh? What’s happening? It’s simple for those who learn JS, right? When we have two separate objects no matter how similar they are inside, they are still two different objects due to different device addresses.

So the solution here will be quite “clumsy” and more complex than we thought.

Wow? What just happened? Let me explain a bit.

Considering the hashTable object, we will use it to distinguish whether the object in the array is a duplicate or not. But because it is just a normal object like any other object, it also means that it cannot distinguish a string and a number when they have the same value.

Well then, how can we use hashTable to distinguish duplicate objects? Calm down and pay attention to stringify . It has done that itself when combined with that hashTable .

The story is now understandable again. See, removing the duplicate element from the array is an old problem but it’s not that simple!

2. Should Object.is () be used for absolute comparison

JS is a loose language, it is lax in many places, but these places sometimes cause quite uncomfortable moments for users. Typically the comparison in JS, is == (type – converting comparisons) and === (strict comparison).

Great in that:

But annoyed that:

Should the expert he devised Object.is() from version ES6 to solve some slightly crazy situation of absolute comparisons === . The nature of Object.is() is the same as === , but it works quite well in some special cases that === not do.

The Mozilla team doesn’t think Object.is() is a stricter comparison than === , saying they should only see this method when used with NaN , -0 and +0 . But I find it quite useful!

3. Insert the element into the array

“It’s an old one again .

Do not assert yet when you have not read it, quite useful, believe me! Although the work of inserting elements into arrays is JS dev’s daily job, but here let us drill down on performance a bit!

3.1 Insert element at the end of the array

It is not strange or difficult with the methods that I listed below:

The first two ways will add the element directly to the old array, and the third way it will return a new array. Please try checking again. So, depending on the specific context, choose the appropriate way to use it!

In terms of performance, there are many differences on phones and computers.

  • On the phone:

  • On the computer:

Specific details on each browser you visit the original reference article offline.

3.2 Insert element at the beginning of the array

Insert into the beginning of the array, we will talk about 2 ways:

And we also get performance results when measuring on computers and phones.

  • On the phone

  • On the computer

Specific details on each browser you visit the original reference article offline.

3.3 Insert element in the middle of the array

Inserting in the middle of the array, I only discuss one way so there is no need to compare performance anymore.

4. Did you really understand the passing reference mechanism of JS?

As a JS dev, I bet you’ve heard this sentence somewhere before: “JavaScript is pass-by-value” . I would like to excuse myself not to translate this sentence here because of my limited English knowledge. To consider the meaning of this saying, see the following example:

“Fuzzy chicken thread” would ask: “Oh, I thought it must be {'belongsTo' : 'A Group'} , right? If I met this question, I would have … from the parking lot. .

Come on, let’s analyze together to clarify!

I have marked the numbers on the me variables so we can follow them easily. First, we declare a variable me#1 , which means that a memory cell (temporarily called me_mem ) is used and me#1 points to that me_mem .

When we call the function myTeam(me) transmission me#1 is on, right now, JS will pass reference object me#1 this as one value (passing the reference to me#1 object as value). Because it is an object and the function itself itself, in other words, creates two references to the same object. So me#2 also points to me_mem .

And in the step of assigning me#2 to me#3 , me#2 has a reference to a new device, the memory of me#3 points to, different from the me_mem memory that it is pointing. Therefore, me#2 will be changed, not me#1 as many people think. So when the show shows me#1 ‘s value, it’s still the original value.

A second example to gain a deeper understanding:

After having experience with the above example and reading more closely in this second example, we may not be surprised at the final result.

The working mechanism of JS is still the same. But let us note in the function myGroup(me) , we make changes to the value of the attribute inside me#2 , that is to change the main me_mem memory that me#2 is referring to. This results in me#1 being called, as well as changing its value as it is referring to me_mem .

That’s amazing, aren’t you, “JavaScript is pass-by-value” .

5. Have fun at the end of the lesson with 3 tips

I have reached the end of the lesson, after 4 difficult tricks that are easy to get, strangely strange, this last part I would like to share 3 small but extremely useful tips. They make our code clean and our logic easier.

5.1 Get the array element from the end of the array

This is for those who forget. This approach is quite common and effective, but rarely used.

5.2 Shorten conditions and execution orders

Suppose, for example, that you have a function that only works when certain conditions are true.

Now your code will be shorter and look a lot more dangerous by writing the following:

It is completely equivalent to the above code only.

5.3 Assign default values ​​using ||

This is also a good trick used by JS devs when assigning a default value to a variable in case that variable is valued as falsy value such as null , undefined , false , NaN , ….

And the application of these “double dashes” is a classic. For example, in writing a method for both a string and an argument, it is possible to use:

You all see that the bottom line is || right?

Conclude

So we went through 5 tips in this article. Pretty long right?

Although there are very familiar things when working with JS such as removing duplicate elements in arrays or adding elements to arrays, passing parameters to functions, or the ways that we still use everyday, I bet that My writing brings more or less knowledge in several aspects of these tips. Hopefully the article will bring some useful things for you.

If you have questions or similar tips, please leave a comment below. Thank you for patiently reading here!

 

Reference http://jstips.co

Share the news now

Source : Viblo