Table of Contents
Introduction
We all know how Javascript development services play a vital role in every organization from an interactive to a responsive web design javascript is used.
From e-commerce to Mobile app development javascript is involved for which various frameworks like Angular to React.js are widely being used.
Javascript has always been talked about among web developers with its usual updates, functionalities and features that it offers which may appear complicated as well.
Therefore we have listed various types of tips and tricks that can make your coding quite easy and scalable.
Tips and tricks in javascript coding
1. Reverse a string
By following the below code you can reverse a one-liner string in a reverse Javascript code.
const reversedString = str.split('').reverse().join('');
By adding this code it will split the string into an array of characters then reverse characters, and join them back together into a string.
2. Sum of array elements
Javascript offers a code which allows you to find the sum of an array. You can use the reduce( )
that performs over each element in an array and reduces it into a single value.
const numbers = [1, 2, 3, 4, 5]; const sum = numbers.reduce((total, number) => total + number, 0);
console.log(sum); // 15
Javascript offers In the above code the first argument of the reduce( )
is the callback function taking two parameters total and number.
The total parameter over here is the running total array and the number is the current element that is being processed.
Here, the second argument of the reduce( )
method is the initial value of the total parameter. In this case, it’s set to 0.
3. Largest and smallest number in array
This one-liner can be used in JavaScript to get the highest and smallest number in an array.
const numbers = [11, 2, 9, 6, 19];
console.log(Math.max(...numbers)); // 19console.log(Math.min(...numbers)); // 2
This code passes each value in the array as an argument to the Math. max( )
and Math. min( )
methods using the spread operator (...)
.
The greatest and smallest values in the array are then returned by these functions, in that order.
4. Remove duplicates from array
Javascript makes it possible to remove duplicate values from an array where you can apply the set
of objects as well as the spread operator (...)
.
const numbers = [2, 3, 7, 7, 2];const uniqueNumbers = [...new Set(numbers)];
console.log(uniqueNumbers); // [2, 3, 7]
const numbers = [2, 3, 7, 7, 2];
const uniqueNumbers = [...new Set(numbers)];
console.log(uniqueNumbers); // [2, 3, 7]
So, when you create a new set
of objects by passing the array as its parameter. You need to ensure that unique values are used. After this, you use the spread operator, where you can convert the set back into an array.
5. Looping objects
The object. entries( ) is the method that is used that return an array of an object’s key-value pairs. Moreover, you’re allowed to use this method to loop through an object’s properties and perform operations on them as well
const person = {
name: 'Techvoot',
age: 33,
city: 'Ahmedabad'
};
for (const [key, value] of Object.entries(person)) {
console.log(`${key}: ${value}`);
}
If we look at the code we have an object with three properties: name, age and city.
Over here the key-value pairs of the person object are created as an array using the object.entries( ) function.
Then, we go through the array using a for...of loop, breaking each key-value pair into variables key and value. Lastly, we use a template literal to record the key and value to the console.
6. Copy to clipboard
This is one trick that the clipboard API offers a simple way to allow you to copy text on the clipboard in Javascript.
function copyToClipboard(text) {
navigator.clipboard.writeText(text);
}
function copyToClipboard(text) {
navigator.clipboard.writeText(text);
}
So, inside the function command, the navigator.clipboard.writetext()method is given with the argument of text allowing us to write the content on the clipboard.
7. Offline/online status
If you are willing to check the user’s online/offline status on the application using Javascript then this is the tip that can help you out.
if (navigator.onLine) {
console.log('User is online');
}
else {
console.log('User is offline);
}
The boolean value returned by this attribute indicates whether the browser is online or offline at the moment.
8. Remove flashy value
Javascript allows you to remove flashy values from an array using the filter( ) method which includes false,0,’ ‘, null, undefined, and NaN.
const arr = [1, 2, 0, '', undefined, null, 3, NaN, false];
const filteredArr = arr.filter(Boolean);
console.log(filteredArr); // [1, 2, 3]
Javascript Boolean type is passed as the callback ( ) to filter( ). The boolean( ) is a built-in function in Javascript that returns true and falsy values.
In this code, Boolean is passed as the callback function to filter(). The Boolean() function is a built-in function in JavaScript that returns true for truthy values and false for falsy values.
Filter() will eliminate any false values from the array arr and return a new array filtered. Arr with only truthy values by passing Boolean as the callback function.
9. Fallenting an array
To flatten a multidimensional array in JavaScript, you can use the flat() method. The flat() method creates a new array with all sub-array elements systematically combined into it to the designated depth.
const multiDimensionalArray = [[1, 2], [3, 4, [5, 6]]];
const flattenedArray = multiDimensionalArray.flat(2);
console.log(flattenedArray); // Output: [1, 2, 3, 4, 5, 6]
The coding of, multiDimensionalArray is a two-dimensional array with two nested arrays. By calling the flat() method with a depth of 2, all sub-array elements are combined into a single flat array.
10. Accessing custom attributes
You get an advantage in HTML that data attributes provide a way to store additional data in an element. To access these in JavaScript, you can use the dataset property of the element.
(div id="myDiv" data-name="Techvoot" data-age="33")(/div)
To access the data-name and data-age attributes of the div element using the dataset property, you can use the following JavaScript code.
const myDiv = document.getElementById('myDiv');
const name = myDiv.dataset.name;
const age = myDiv.dataset.age;
console.log(name); // "Techvoot"
console.log(age); // "35"
myDiv.dataset returns an object that contains the values of all the custom data attributes on the div element.
11. Create an array from iterables
A built-in JavaScript function called an array. from() builds a new array from an iterable or array-like object.
// Converting String to an array
const str = "Rabi";
const arr = Array.from(str);
console.log(arr); // Output: ["R", "a", "b", "i"]
// Converting Set to an array
const set = new Set([1, 2, 3, 3, 4, 5]);
const arr = Array.from(set);
console.log(arr); // Output: [1, 2, 3, 4, 5]
It’s a method that can be used in converting various data structures such as strings, Sets, and Maps into an array.
Conclusion
So, there is no doubt that even if you feel your Javascript is a bit complicated then these tips and tricks will help you sort out your codes and make them less complicated, easy to understand while you are creating a robust and effective website.