1. Empty or truncate the array

The easiest way to empty or truncate an array without reassigning it is to change its Length property value:

[JavaScript]

Plain text view
Copy the code

?
1
2
3
4
5
6
7
8
const arr = [11, 22, 33, 44, 55, 66];
// truncanting
arr.length = 3;
console.log(arr);
/ / = > [11, 22, 33]
// clearing
arr.length = 0;
console.log(arr);
/ / = > []
console.log(arr[2]);
//=> undefined

2. Simulate named parameters using object destructuring

When you need to pass a set of optional variables to a function, you are probably already using configuration objects, as follows:

[JavaScript]

Plain text view
Copy the code

?
1
2
3
4
5
6
7
doSomething({ foo:
'Hello'
, bar:
'Hey! '
, baz: 42 });
function
doSomething(config) {
const foo = config.foo ! == undefined ? config.foo :
'Hi'
;
const bar = config.bar ! == undefined ? config.bar :
'Yo! '
;
const baz = config.baz ! == undefined ? config.baz : 13;
// ...
}

This is an old but valid pattern that attempts to emulate named parameters in JavaScript. The function call looks fine. On the other hand, configuring object processing logic is unnecessarily verbose. Using ES2015 object destructuring, you can get around this shortcoming:

[JavaScript]

Plain text view
Copy the code

?
1
2
3
function
doSomething({ foo =
'Hi'
, bar =
'Yo! '
, baz = 13 }) {
// ...
}

If you need to make configuration objects optional, that’s easy:

[JavaScript]

Plain text view
Copy the code

?
1
2
3
function
doSomething({ foo =
'Hi'
, bar =
'Yo! '
, baz = 13 } = {}) {
// ...
}

3. Use object deconstruction to work with arrays

Object destructuring can be used to assign array items to variables:

[JavaScript]

Plain text view
Copy the code

?
1
2
const csvFileLine =
'1997,John Doe,US,[email][email protected][/email],New York'
;
const { 2: country, 4: state } = csvFileLine.split(
', '
);

4. Use range values in switch statements

Note: After some thought, I’ve decided to separate this tip from the others in this article. This is not a time-saving technique and does not apply to real-world code. Remember: The “If” statement is always better in this case.

Unlike the other tips in this article, it’s more of a curiosity quest than something to actually use.

However, for historical reasons, I’ll keep it for this article.

Here’s a simple trick to use range values in switch statements:

[JavaScript]

Plain text view
Copy the code

?
01
02
03
04
05
06
07
08
09
10
11
function
getWaterState(tempInCelsius) {
let state;
switch
(
true
) {
case
(tempInCelsius < = 0): state =
'Solid'
;
break
;
case
(tempInCelsius > 0 && tempInCelsius < 100):
state =
'Liquid'
;
break
;
default
:
state =
'Gas'
;
}
return
state;
}

5. Await multiple async functions with async/await

You can await multiple async functions using promise. all.

[JavaScript]

Plain text view
Copy the code

?
1
await Promise.all([anAsyncCall(), thisIsAlsoAsync(), oneMore()])

6. Create pure objects

You can create a 100% pure Object that inherits no properties or methods from Object (for example, constructor, toString(), and so on).

[JavaScript]

Plain text view
Copy the code

?
1
2
3
4
5
const pureObject = Object.create(
null
);
console.log(pureObject);
/ / = > {}
console.log(pureObject.constructor);
//=> undefined
console.log(pureObject.toString);
//=> undefined
console.log(pureObject.hasOwnProperty);
//=> undefined

7. Format JSON code

Json.stringify can do more than simply convert objects to strings. You can also use it to format JSON output:

[JavaScript]

Plain text view
Copy the code

?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
const obj = {
foo: { bar: [11, 22, 33, 44], baz: { bing:
true
, boom:
'Hello'
}}
};
// The third parameter is the number of spaces used to
// beautify the JSON output.
JSON.stringify(obj,
null
, 4);
/ / = > "{
// => "foo": {
// => "bar": [
/ / = > 11,
/ / = > 22,
/ / = > 33,
/ / = > 44
/ / = >],
// => "baz": {
// => "bing": true,
// => "boom": "Hello"
/ / = >}
/ / = >}
/ / = >}"

8. Remove duplicate elements from array

By using the set syntax and Spread operator, you can easily remove duplicates from an array:

[JavaScript]

Plain text view
Copy the code

?
1
2
3
const removeDuplicateItems = arr => [...
new
Set(arr)];
removeDuplicateItems([42,
'foo'
, 42,
'foo'
.
true
.
true
]);
//=> [42, "foo", true]

Tiling multidimensional arrays

Using Spread(Spread), it is easy to tile a nested multidimensional array:

[JavaScript]

Plain text view
Copy the code

?
1
2
const arr = [11, [22, 33], [44, 55], 66];
const flatArr = [].concat(... arr);
//=> [11, 22, 33, 44, 55, 66]

Unfortunately, the above method only works for two-dimensional arrays. By recursion, however, we can tile nested arrays of any dimension.

[JavaScript]

Plain text view
Copy the code

?
1
2
3
4
5
6
7
8
unction flattenArray(arr) {
const flattened = [].concat(... arr);
return
flattened.some(item => Array.isArray(item)) ?
flattenArray(flattened) : flattened;
}
const arr = [11, [22, 33], [44, [55, 66, [77, [88]], 99]]];
const flatArr = flattenArray(arr);
//=> [11, 22, 33, 44, 55, 66, 77, 88, 99]

That’s it! I hope these clever tricks will help you write better, prettier JavaScript.