JavaScript is responsible for all the interactivity on a webpage. The language enables web browsers to create a dynamic and interactive user experience. Companies use JavaScript to develop robust and highly efficient frameworks and systems.
It is why the demand for JavaScript developers is high. But to be a proficient JavaScript developer, you must learn how to write optimized JavaScript code. Optimized code combines cleverly programmed logic and a few tips and tricks to improve the performance and speed of code execution.
Here are some advanced JavaScript hacks for programmers to optimize and improve the performance of their JS code.
1. Use array filter
In JavaScript, you often need to use arrays. This little hack will allow you to bucket out elements from the array pool based on a preset condition that you pass as a function. You can create a callback function for non-required elements according to the use case.
Here is an example where we separate the null elements from the other aspects of the array.
schema = [“hi”,”Hello World!”,null, null, “goodbye”]
schema = schema.filter(function(n) {
return n
});
Output: [“hi”,” Hello World!”, “goodbye”]
This JavaScript trick will save you time and some lines of code while improving the performance of the code.
2. Using length to delete empty in an array
While you can resize and empty an array, the conventional way of writing a dedicated function works on the array, but there’s a more thoughtful way to achieve this.
You can achieve the same goal by use of array.length.
Here is an example to delete n elements using array.length.
array.length = n
code:
var array = [1, 2, 3, 4, 5, 6];
console.log(array.length); // 6
array.length = 3;
console.log(array.length); // 3
console.log(array); // [1,2,3]
You can also use the array.length to empty the array using array.length = 0, like this:
Example:
var array = [1, 2, 3, 4, 5, 6];
array.length = 0;
console.log(array.length); // 0
console.log(array); // []
It is the most preferred way to resize/unset an array, and experienced programmers use it to ensure that their code is optimized and there are no stray elements in the array.
3. Nested ternary operator
We can simplify the use of multiple conditional expressions in our JavaScript code with the use of nested ternary operation.
condition: ? expressionIfTrue : expressionIfFalse
instead of
if else-if else.
The problem with using too many if else-if else in the JS code is that the complicated nesting not only increases the execution time, such code is not clean and is hard to read and maintain.
Let’s understand the nested ternary operator with an example.
Support you have a blog home page where you want to itemsPerPage number of posts per page. Now here are three scenarios that are possible:
- If the number of articles is less than the itemsPerPage, the value of the pages variable should be 1.
- If the number of articles is more than the itemsPerPage, then the value of our pages variable should be equal to the itemsPerPage.
- If the number of articles is less than the itemsPerPage, the value of our pages variable should be the same as the number of pages.
This can be easily implemented with a nested ternary operator like this:
const articles = Array.from({ length: 120 }, (_, index) => index);
const paginate = (items, itemsPerPage = 10) => {
const pages =
itemsPerPage > items.length
? 1
: Math.ceil(items.length / itemsPerPage) > itemsPerPage
? itemsPerPage
: Math.ceil(items.length / itemsPerPage);
return Array.from({ length: pages }, (_, index) => {
const start = index * itemsPerPage;
return items.slice(start, start + itemsPerPage);
});
};
console.log(paginate(articles));
4. Easy way to invert an integer
One of the most commonly asked JavaScript questions in interviews is how you can reverse a positive or negative integer within reasonable limits.
It’s not just a tricky JavaScript question but also has applications in the real world, like in eCommerce and wallet applications.
First, you can check if the input is within the valid limits. If it is, then we take the absolute value of input and divide it by the integer 10 in each loop until the number is zero. We store the last digit of the number in each loop. Then we multiply each value by 10 and add it to the last digit. This is how we reverse the given integer.
Here’s the code:
const reverseInteger = (input) => {
const checkNumber =
input > 2 ** 31 || input < -(2 ** 31) || typeof input !== ‘number’;
if (checkNumber) return 0;
let number = Math.abs(input);
let result = 0;
while (number !== 0) {
let lastDigit = number % 10;
result = result * 10 + lastDigit;
number = Math.floor(number / 10);
}
return input < 0 ? -result : result;
};
console.log(reverseInteger(15345345345534534535334523));
console.log(reverseInteger(-15345345345534534535334523));
console.log(reverseInteger(123));
console.log(reverseInteger(‘123’));
console.log(reverseInteger(-456));
console.log(reverseInteger(0));
But there is an easier way to do the same. We can convert number to string and do all the operations with strong methods, like this:
const reverseInteger = (input) => {
const checkNumber =
input > 2 ** 31 || input < -(2 ** 31) || typeof input !== ‘number’;
if (checkNumber) return 0;
const reversedInteger = parseInt(
Math.abs(input).toString().split(”).reverse().join(”)
);
return input < 0 ? -reversedInteger : reversedInteger;
};
console.log(reverseInteger(15345345345534534535334523));
console.log(reverseInteger(-15345345345534534535334523));
console.log(reverseInteger(123));
console.log(reverseInteger(‘123’));
console.log(reverseInteger(-456));
console.log(reverseInteger(0));
Conclusion
Start improving your JavaScript skills with these optimizations. As you gain experience, you will learn more ways to optimize your code.
Talent500 is the platform for Indian developers to explore global job opportunities. Sign up here and get discovered by Fortune 500 companies and the best startups.
Add comment