9 Modern && Practical JavaScript Code Snippets
By: Kesk - -
Tags: Javascript Tips, JavaScript, Javascript Development, Web Development, Software Development

9 Modern && Practical JavaScript Code Snippets

Photo by Eugene Shelestov en Pexels

This article shows you how to resolve everyday JavaScript tasks by writing less code and using the language's latest features more straightforwardly.

There are ten small hacks that you can use in any part of your code without any difficulty.

Let’s start

Index

Transform && Filter an Array at the same time. Fetch && Retry. Recursive setTimeout. Get Fields and Length from an Array by Destructuring. Reverse a String. Clear an Array. Trimming an Array. Extending an Array. Create an Array from an Object.

1. Transform && filter an Array at the same time

We can transform and filter an Array using the map() and the filter() method in two steps, but why we don't transform it and filter in one step?

In two steps with filter() and map():

let anArrray= [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; let by2= anArrray

.filter( (n) => n >= 5 )

.map( (n) => n * 2);

Result in the google chrome console.

In one step with flatmap():

let anArrray= [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; let by2= anArrray.flatMap( (n) => n >=5 ? [ n * 2 ] : [] );

Result in the google chrome console.

2. Fetch && Retry

We can use the ES6 Fetch method to recover data from the server, but sometimes, the server or the network will be down, and we will not receive the correct answer. For example, The server can fail because it is busy. In this case, we can retry the call.

Using promises:

fetch("/someUrl/json").then( function handleResponse (response) {

if (response === 200) {

return response;

} else {

fetch("/some/json").then(handleResponse);

}

catch (err{

console.error(err);

}

});

Code image for small screens.

Using a loop and ES7 async-await

n: Number of retries

const fetch_retry = async (url, options, n) => {

let error;

for (let i = 0; i < n; i++) {



try {

response = await fetch(url, options);

if (response === 200) {

return response;

}else{

throw new Error(response)

}

} catch (err) {

error = err;

//1.

if (i + 1 === n) throw err;

}

}

throw error;

}; let response = fetch_retry("/someUrl/json", options, 10);

Code image for small screens.

If the number of retries is reached we trigger an error.

Using recursion and ES7 async-await

n: Number of retries

const fetch_retry = async (url, options, n) => {

try {

response = await fetch(url, options);

if (response === 200) {

return response;

}else{

throw new Error(response)

}

} catch(err) {

//.1

if (n === 1) throw err;



//2.

response = await fetch_retry(url, options, n - 1);

if (response === 200) {

return response;

}else{

throw new Error(response)

}

}

};

let response = fetch_retry("/someUrl/json", options, 10);

Code image for small screens.

If the number of retries is reached we trigger an error and the execution is stopped. We retry the request by calling the fetch_retry function and decreasing the number of attempts.

3. Recursive setTimeout()

To execute a function at regular intervals to we can use the setInterval() method. This choice is the right choice as long as the function to be executed fast and synchronous. In another case, it is better to call setTimeout() recursively.

With setInterval()

const everySecond= () => console.log("Second:" +new Date().getSeconds()); setInterval(everySecond, 1000);

Result in the google chrome console.

With setTimeout()

const everySecond= () => console.log("Second:" +new Date().getSeconds()); setTimeout( function namedFunction() {

everySecond();

setTimeout(namedFunction, 1000);

}, 1000);

Result in the google chrome console.

4. Get Fields and Length from an Array by Destructuring

I think the example is self-explanatory:

let anArray= [ "a", "b", "c", "d", "e", "f", "g", "h"];

let { 0: v1, 2: v2, length } = anArray;

Result in the google chrome console.

5. Reverse a String

const hello = "Hello Kesk!";

const reverseString = (s) => [...s].reverse();

With Destructuring and the Reverse method, we obtain the array with the letters in inverse order corresponding to the string “s”:

Result in the google chrome console.

And now, we only have to join all the letters again using the “join” method, without spaces in this case.

const hello = "Hello Kesk!";

const reverseString = (s) => [...s].reverse().join('');

reverseString(hello);

Result in the google chrome console.

6. Clear an Array

We don’t have an “Empty” method for empty the array, but we have the length property. This property of the Arrays reflects the number of fields contained in the array. If we set this property to zero, the array is emptied.

let anArray= [ "val1", "val2", "val3", "val4" ];

anArray.length = 0; anArray.forEach(element => console.log(element))

Result in the google chrome console.

Or:

let anArray= [ "val1", "val2", "val3", "val4" ];

anArray = []; anArray.forEach(element => console.log(element))

7. Trimming an Array

Also, we can Trim an Array using this property:

let anArray= [ "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7"];

anArray.length = 4; anArray.forEach(element => console.log(element))

Result in the google chrome console.

8. Extending an Array

Or we can extend the Array in the same way:

let anArray= [ "val1", "val2", "val3" ];

anArray.length = 10; anArray.forEach(element => console.log(element))

Result in the google chrome console.

9. Create an Array from an Object

We can use Object.keys() and map() to do this simply:

const kesk = {

name: "Kesk",

age : 36,

eyes: 'green'

} const convertoObjectToArray = obj => Object.keys(obj).map(e =>

[e, obj[e] ]); convertoObjectToArray(kesk);

Result in the google chrome console.

Conclusion

I hope you liked these little “tricks” and that they help you in your every day.

More tips here:

Thank you for reading to me!