JavaScript Tips For Developer 2020

There are a few javascript tricks that I want to share. You will learn something new to become the best javascript developer.

Image for post
Image for post

Combine/flatten the arrays in the array.

Array has a method called Array.flat, it needs a depth parameter, which indicates the depth of array nesting, the default value is 1. However, if we don’t know what to do with the depth, we need to flatten it all and just use it Infinity as a parameter.

const array = [[10], 25, [50, [100, 200,[300]]]];array.flat(Infinity);
// output: [10, 25, 50, 100, 200, 300]

Prevent code crash

Unpredictable behavior in the code is bad, but if you have this behavior, you need to deal with it. For example, common errors, try to obtain undefined/null attributes, etc., will report this error.

const found = [{ name: "John" }].find(i => === 'Mark')console.log( 
// TypeError: Cannot read property 'name' of undefine

We can avoid it like this:

const found = [{ name: "John" }].find(i => === 'Mark') || {}  console.log( // undefined

The best way to pass parameters

A best use case for this method is styled-components that in ES6, we can pass template characters as function parameters without using square brackets. If you want to achieve the function of formatting/converting text, this is a good trick:

const generateList = (raw) =>   raw.join().trim().split("\n").map((s, i) => `${i + 1}. ${s}`).join("\n");  generateList` 
Hello, Jacob
Hello, Mark
// 1. Hello, Jacob
// 2. World, Mark

Swap variables

Using destructuring assignment syntax, we can easily swap variables using destructuring assignment syntax

let a = 10, b = 20;
// Wrong way
a = b;
b = a;
// a= 20, b= 20
// Correct way
[a, b] = [b, a]
// a= 20, b: 10

Use the value as a parameter of the Math method.

When we use Math.max or Math.min in the array to find the maximum or minimum value, we can operate as follows:

const numbers = [100, 200, -2000, 1000, 30000, -40000];  
// 30000
// -40000

Use the value array as the parameter of the function.

In some cases, we need to collect the value into an array and then pass it as a function parameter. Use ES6, the operator can use the extended (…), and from [arg1, arg2] > (arg1, arg2) extracts the array:

const parts = {   
first: [0, 2],
second: [1, 3],
["Hello", "World", "JS", "Tricks"].slice(
// ["World", "JS"]

Generate a specified range of numbers.

In some cases, we will create an array between two numbers. Suppose we want to judge whether someone’s birthday is within a certain range of years, then here is a very simple way to achieve it.

let start = 1900, end = 2000;   
[ Array(end + 1).keys()].slice(start);
// [ 1900, 1901, ..., 2000]
// There is this way, but it is not stable for a very wide range Array.from({ length: end - start + 1 }, (_, i) => start + i);

Sort alphabetically.

In localization, some languages ​​may have problems with dictionary sorting, as shown below.

// Wrong approach 
["a", "z", "ä"].sort((a, b) => a - b);
// ['a', 'z', 'ä']
// Correct approach
["a", "z", "ä"].sort((a, b) => a.localeCompare(b));
// [ 'a', 'ä', 'z' ]

localeCompare(): Compare two strings in local specific order.

Hide privacy

When you need to block any variables (not passwords), the following approach can quickly help you do it:

const userPass= "password";  userPass.substr(-2).padStart(userPass.length, "*");  
// ******rd

Optional chaining

Have you ever had the problem of accessing a nested object property, without knowing if the object or one of the sub-properties even exists? You will probably end up with something like this:

let data;if(myObj && myObj.firstProp && myObj.firstProp.secondProp && myObj.firstProp.secondProp.actualData)
data = myObj.firstProp.secondProp.actualData

There is a better way, it is called optional chaining:

data = myObj?.firstProp?.secondProp?.actualData

I think it is the best way of checking nested properties and makes the code way cleaner.

Written by

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store