12 Super Useful techniques in JavaScript

In my opinion, obligatory knowledge

Kesk -*-
Kesk -*-
Oct 31 · 5 min read
A woman with her eyes wide open
A woman with her eyes wide open
Image by Gratisography in Pexels

In this article, I compile some of the JavaScript “techniques” that I usually use in my day-to-day life, saving a lot of time. I hope you find them useful!

1. Create a Generic function

Let’s imagine that we want to develop a generic function, given some parameters and a function. This function is executed then with these parameters.
For example, a calculator with N parameters and N operations. You can easily achieve this using the spread operator and the reduce function:

function calculator(operation, ...numbers) {
return operation(...numbers);
}
function add(...numbers) {
return numbers.reduce( (total, num) => total + num, 0);
}
function subtract(...numbers) {
return numbers.reduce( (total, num) => total - num, 0);
}
function multiply(...numbers) {
return numbers.reduce( (total, num) => total * num, 1);
}
console.log(calculator(add, 1, 2, 3, 4, 5));
console.log(calculator(subtract, 10, 2, 1));
console.log(calculator(multiply, 2, 2, 2, 2));
Image for post
Image for post
Different operations with our generic function

2. Switch with ranges

Sometimes you would probably have found useful to use ranges in a Switch sentence. Here is an example of how to do it:

function chooseSportByTemperature(fahrenheit) { 
let sport;
switch (true) {

case (fahrenheit >= 15 && fahrenheit <=20):
sport = 'Running';
break;
case (fahrenheit > 20 && fahrenheit <= 30):
sport = 'Cycling';
break;
case (fahrenheit > 30):
sport = 'Stay in home';
break;
default:
sport = 'Sex';

}
return sport;
}

3. Grouping multiple switch cases

A clean way to group case sentences:

function setMyValueByValue(value) { 
let myValue;
switch (value)
{
case "value1":
case "value2":
case "value3":
myValue = "My value 1-2-3"
break;
case "value4":
myValue = "My value 4"
break;
default:
myValue = "Default value"
}
return myValue;
}
console.log(setMyValueByValue("value1"));
console.log(setMyValueByValue("value2"));
console.log(setMyValueByValue("value3"));
console.log(setMyValueByValue("value4"));
console.log(setMyValueByValue("value5"));
Image for post
Image for post
Grouping multiple switch cases.

4. Wait to multiple asynchronous functions with async/await

It is possible to wait to await the completion of multiple asynchronous functions using (Promise.all) inside the async function.

function resolveAfter1Seconds() {
return new Promise(resolve => {
setTimeout(() => {
resolve('resolved');
}, 1000);
});
}
function resolveAfter2Seconds() {
return new Promise(resolve => {
setTimeout(() => {
resolve('resolved');
}, 2000);
});
}
function resolveAfter3Seconds() {
return new Promise(resolve => {
setTimeout(() => {
resolve('resolved');
}, 3000);
});
}
function resolveAfter4Seconds() {
return new Promise(resolve => {
setTimeout(() => {
resolve('resolved');
}, 4000);
});
}
async function asyncFunction() {
console.log('start');
const result = await Promise.all(

[resolveAfter1Seconds(),
resolveAfter2Seconds(),
resolveAfter3Seconds(),
resolveAfter4Seconds()])
console.log(result); //resolved after 4 seconds !
console.log('end');
}
asyncFunction();

5. Flattening bidimensional arrays in one step

const multidimensionalArray = [1,2, [3, 4], [5, 6], 7, [8] ];const flatArray = (original) => [].concat(...original);const flattenedArray = flatArray(multidimensionalArray);
Image for post
Image for post
Bidimensional flattened Array

6. Flattening multidimensional arrays in one step

Using the flat() method, we can create a new array with all sub-array elements concatenated into it recursively up to the specified depth.

const multidimensionalArray = [0, 1, 2, [[[3, 4, 5]]]];console.log(multidimensionalArray.flat());console.log(multidimensionalArray.flat(3)); //depth 3.
Image for post
Image for post
Multidimensional flattened array

7. Create pure objects in JavaScript

It is often interesting to create pure JavaScript objects that do not inherit any Object properties. Achieve this is as simple as doing the following:

const car = {type:"Ford", model:"250", color:"black"};console.log(car);
console.log(car.constructor);
console.log(car.toString);
console.log(car.hasOwnProperty);
Image for post
Image for post
Regular JavaScript Object
const  pureCar = Object.create(null);console.log(pureCar);
console.log(pureCar.__proto__);
console.log(pureCar.constructor);
console.log(pureCar.toString);
console.log(pureCar.hasOwnProperty);
Image for post
Image for post
Pure JavaScript Object

8. Remove duplicates elements in an Array in one step

To remove duplicate elements in an array, you can use destructuring and ES6 Set:

const removeDuplicatesFromArray = arr => [...new Set(arr)];

removeDuplicatesFromArray([1,1,2,3,4,4,4,true,true,'foo','foo']);
Image for post
Image for post

9. Display in the console when a page has started and finished loading

<script>
window.onload=() =>{console.log('Start');}
window.onunload=() =>{console.log('Finish');}
</script>
Or better:<script>
window.onload=() =>{console.time('pageLoadingTime');}
window.onunload=() =>{console.timeEnd('pageLoadingTime');}
</script>

You can use also the console.time(‘a unique name’) and console.timeEnd(‘a unique name’) functions that starts and ends a timer you to track how long an operation takes.

Image for post
Image for post
Using console.time() and console.timeEnd()

10. Button to print the current page

<input type="button" value="Print this page!" onclick="window.print()">

11. Rounding off numbers

We can round to the nearest integer, round down, or round up. JavaScript uses three methods to achieve this: Math

let myNumber= 1.56789;
myNumber = myNumber.toFixed(2);
Image for post
Image for post
myNumber round to two decimals

The output is a string that needs to be passed to the parseFloat() function to return a number. Unfortunately, this is really slow. But if you need precision, this is the better way.

Another way to do this is to use Math.round to rounds to the nearest integer:

let myNumber= 1.56789;
Math.round(myNumber);
Image for post
Image for post
myNumber round with Math.round

Or Math.floor() that rounds down and Math.ceil() to rounds up.

Note that rounding is not the same as truncating:

let myNumber= 1.56789;
Math.trunc(myNumber);
Image for post
Image for post
myNumber truncated with Math.trunc

Math.trunc() removes all the fractional digits.

12. Empty an array

As easy as assigning a zero value to his length property:

let myArray = [1,2,3,4,5,6,7,8,9,10];
myArray.length = 0;
Image for post
Image for post
My new empty array

Conclusion

I hope this article has been useful and enjoyable for you. By combining what language brings us, we often achieve powerful and practical things, such as creating a generic calculator in a few steps.

More in: 12 More New Super Useful Tricks In JavaScript

Thanks for reading me! Take care!

JavaScript In Plain English

New JavaScript + Web Development articles every day.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

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