• 8 Useful JavaScript Tricks
  • By Milos Protic
  • Translation from: The Gold Project
  • This article is permalink: github.com/xitu/gold-m…
  • Translator: Xuyuey
  • Proofreader: Twang1727, smilemuffie

introduce

Each programming language has its own unique techniques. Many of these are well known to developers, but some of them are quite hackish. In this article, I’m going to show you some techniques that I’ve found useful. Some of them I’ve used in practice, while others are new approaches to old problems. Enjoy!

1. Ensure the length of the array

Have you ever seen a situation when working with a grid structure where you have to recreate the original data if the rows are not equal in length? Well, I have! To ensure that each row has the same length of data, you can use the array. fill method.

let array = Array(5).fill(' ');
console.log(array); // Output (5) ["", "", "", ""]
Copy the code

2. De-duplicate arrays

ES6 provides several very concise methods for de-duplicating arrays. Unfortunately, they are not suitable for handling arrays of non-primitive types. You can read more about it later in the tricky Array Replay article. Here we are only concerned with array deduplicating of the basic type.

const cars = [
    'Mazda'.'Ford'.'Renault'.'Opel'.'Mazda'
]
const uniqueWithArrayFrom = Array.from(new Set(cars));
console.log(uniqueWithArrayFrom); // output ["Mazda", "Ford", "Renault", "Opel"]

const uniqueWithSpreadOperator = [...new Set(cars)];
console.log(uniqueWithSpreadOperator);// output ["Mazda", "Ford", "Renault", "Opel"]
Copy the code

3. Concatenate objects and arrays of objects with extension operations

Merging objects is not a rare problem, and chances are you’ve already encountered it and will again in the near future. The difference is that in the past you did most of the work manually, but from now on, you’ll be using the new features of ES6.

// Merge objects
const product = { name: 'Milk'.packaging: 'Plastic'.price: '5 $' }
const manufacturer = { name: 'Company Name'.address: 'The Company Address' }

constproductManufacturer = { ... product, ... manufacturer };console.log(productManufacturer); 
{name: "Company name ", packaging: "Plastic", price: "$", address: "The Company address"}

// Merge the array of objects into one object
const cities = [
    { name: 'Paris'.visited: 'no' },
    { name: 'Lyon'.visited: 'no' },
    { name: 'Marseille'.visited: 'yes' },
    { name: 'Rome'.visited: 'yes' },
    { name: 'Milan'.visited: 'no' },
    { name: 'Palermo'.visited: 'yes' },
    { name: 'Genoa'.visited: 'yes' },
    { name: 'Berlin'.visited: 'no' },
    { name: 'Hamburg'.visited: 'yes' },
    { name: 'New York'.visited: 'yes'}];const result = cities.reduce((accumulator, item) = > {
  return {
    ...accumulator,
    [item.name]: item.visited
  }
}, {});

console.log(result);
/* Output Berlin: "no" Genoa: "yes" Hamburg: "yes" Lyon: "no" Marseille: "yes" Milan: "no" New York: "yes" Palermo: "yes" Paris: "no" Rome: "yes" */
Copy the code

4. Array mapping (Not usedArray.map)

Did you know there’s another way to do Array mapping without using array.map? If you don’t know, keep reading.

const cities = [
    { name: 'Paris'.visited: 'no' },
    { name: 'Lyon'.visited: 'no' },
    { name: 'Marseille'.visited: 'yes' },
    { name: 'Rome'.visited: 'yes' },
    { name: 'Milan'.visited: 'no' },
    { name: 'Palermo'.visited: 'yes' },
    { name: 'Genoa'.visited: 'yes' },
    { name: 'Berlin'.visited: 'no' },
    { name: 'Hamburg'.visited: 'yes' },
    { name: 'New York'.visited: 'yes'}];const cityNames = Array.from(cities, ({ name}) => name);
console.log(cityNames);
/ / output [" Paris ", "Lyon, Marseille," Rome ", ", ", "Palermo," "Genoa", "("," Hamburg ", "New York"]
Copy the code

5. Add object attributes based on the conditions

Now, you no longer need to create two different objects based on conditions to make them have specific properties. The extension operator would be a perfect choice.

const getUser = (emailIncluded) = > {
  return {
    name: 'John'.surname: 'Doe'. (emailIncluded ? {email : '[email protected]' } : null)}}const user = getUser(true);
console.log(user); {name: 'John', surname: 'Doe', email: '[email protected]'}

const userWithoutEmail = getUser(false);
console.log(userWithoutEmail); {name: 'John', surname: 'Doe'}
Copy the code

6. Deconstruct raw data

Have you ever worked with an object that had a lot of properties? I’m sure you have. Probably the most common case is that we have a user object that contains all the data and details. Here, we can call the new ES deconstruction method to handle the big trouble. Let’s look at the following example.

const rawUser = {
   name: 'John'.surname: 'Doe'.email: '[email protected]'.displayName: 'SuperCoolJohn'.joined: '2016-05-05'.image: 'path-to-the-image'.followers: 45. }Copy the code

By splitting the above object into two, we can represent the object in a more context-sensitive way, as follows:

let user = {}, userDetails = {};
({ name: user.name, surname: user.surname, ... userDetails } = rawUser);console.log(user); {name: 'John', surname: 'Doe'}
console.log(userDetails); // Output {email: "[email protected]", displayName: "SuperCoolJohn", joined: "2016-05-05", image: "path-to-the-image", followers: 45 }
Copy the code

7. Set the object property name dynamically

In the past, if we wanted to set an object’s property name dynamically, we had to declare an object first and then assign it a property. This cannot be done in a declarative way. Today, we can do that with the capabilities of ES6.

const dynamic = 'email';
let user = {
    name: 'John',
    [dynamic]: '[email protected]'
}
console.log(user); // Output {name: "John", email: "[email protected]"}
Copy the code

8. String interpolation

Last but not least is the new way of concatenating strings. This is useful if you want to build template strings in a helper program. It makes dynamic concatenation string templates much easier.

const user = {
  name: 'John'.surname: 'Doe'.details: {
    email: '[email protected]'.displayName: 'SuperCoolJohn'.joined: '2016-05-05'.image: 'path-to-the-image'.followers: 45}}const printUserInfo = (user) = > { 
  const text = `The user is ${user.name} ${user.surname}. Email: ${user.details.email}. Display Name: ${user.details.displayName}. ${user.name} has ${user.details.followers} followers.`
  console.log(text);
}

printUserInfo(user);
Email: [email protected]. Display Name: supercooljohn. John has 45 followers.'
Copy the code

conclusion

The world of JavaScript is expanding rapidly. There are so many cool features that you can use at any time. Thorny and time-consuming problems are fading away, and with the new features of ES6, we have a lot of new solutions out of the box.

That’s all I want to share with you today. If you like this post, please retweet or like it.

Thanks for reading, and I’ll see you next time.

If you find any errors in the translation or other areas that need improvement, you are welcome to revise and PR the translation in the Gold Translation program, and you can also get corresponding bonus points. The permanent link to this article at the beginning of this article is the MarkDown link to this article on GitHub.


Diggings translation project is a community for translating quality Internet technical articles from diggings English sharing articles. The content covers the fields of Android, iOS, front end, back end, blockchain, products, design, artificial intelligence and so on. For more high-quality translations, please keep paying attention to The Translation Project, official weibo and zhihu column.