Top 15 JavaScript Tips and Tricks to Increase your Speed and Efficiency

Most programming languages are flexible enough to allow programmers to achieve similar results in a variety of ways. JavaScript isn’t any different. JavaScript is without a doubt one of the coolest languages in the world, and it is growing in popularity by the day. With JavaScript, we frequently find multiple ways to achieve the same result, which can be perplexing at times.

Some of the applications are superior to the alternatives. With our profound expertise in JavaScript, we will happily share a few tips and tricks that would help you. Let’s get started.

1. Swap values with Array Destructuring

The destructuring assignment syntax is a JavaScript expression that allows you to extract values from arrays or properties from objects and store them in separate variables. We can also use it to quickly swap values, as shown below:

let a = 1, b = 2
[a, b] = [b, a]
console.log(a) // result -> 2
console.log(b) // result -> 1

2. Remove duplicates from an Array

This is a very simple trick. Assume we created an array with numbers, strings, and booleans, but the values are repeating themselves multiple times and we want to remove the duplicates. So here’s what we can do:

const array = [1, 3, 2, 3, 2, 1, true, false, true, ‘Kio’, 2, 3];
const filteredArray = […new Set(array)];
console.log(filteredArray) // [1, 3, 2, true, false, “Kio”]

3. Shuffle an Array

Making use of the inbuilt Math.random() method.

const list = [1, 2, 3, 4, 5, 6, 7, 8, 9];
list.sort(() => {
    return Math.random() – 0.5;
});
// Output
(9) [2, 5, 1, 6, 9, 8, 4, 3, 7]
// Call it again
(9) [4, 1, 7, 5, 3, 8, 2, 9, 6]

4. Nullish Coalescing Operator

The nullish coalescing operator (??) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined and otherwise returns its left-hand side operand.

const foo = null ?? ‘my school’;
// Output: “my school”

const baz = 0 ?? 42;
// Output: 0

5. Functional Inheritance

The process of receiving features by applying an augmenting function to an object instance is known as functional inheritance. The function provides a closure scope that can be used to keep some data private. The augmenting function uses dynamic object extension to add new properties and methods to the object instance.

They look like:

// Base function
function Drinks(data) {
  var that = {}; // Create an empty object
  that.name = data.name; // Add it a “name” property
  return that; // Return the object
};

// Function which inherits from the base function
function Coffee(data) {
  // Create the Drinks object
  var that = Drinks(data);
  // Extend base object
  that.giveName = function() {
    return ‘This is ‘ + that.name;
  };
  return that;
};

// Usage
var firstCoffee = Coffee({ name: ‘Cappuccino’ });
console.log(firstCoffee.giveName());
// Output: “This is Cappuccino”

6. Single-liner Palindrome check

Well, this is not a shorthand trick overall but it will give you a clear idea to play with strings.

function checkPalindrome(str) {
  return str == str.split(”).reverse().join(”);
}
checkPalindrome(‘naman’);
// Output: true

7. Simple Swap 2 values using Destructuring

let a = 5;
let b = 8;
[a,b] = [b,a]

[a,b]
// Output
(2) [8, 5]

8. Convert Decimal to Binary or Hexa

We can use some in-built methods like .toPrecision() or .toFixed() to achieve many functionalities while solving problems.

const num = 10;

num.toString(2);
// Output: “1010”
num.toString(16);
// Output: “a”
num.toString(8);
// Output: “12”

9. Short For Loop

You can write less code for a loop like this:

const names = [“Kio”, “Rio”, “Mac”];

// Long Version
for (let i = 0; i < names.length; i++) {
  const name = names[i];
  console.log(name);
}

// Short Version
for (let name of names) console.log(name);

10. Using length to resize and emptying an array

In javascript, we can override a built-in method called length and set its value to whatever we want.

Consider the following example:

let array_values = [1, 2, 3, 4, 5, 6, 7, 8]; 
console.log(array_values.length);
// 8 
array_values.length = 5; 
console.log(array_values.length);
// 5 
console.log(array_values);
// [1, 2, 3, 4, 5]

It can also be used in emptying an array, like this:

let array_values = [1, 2, 3, 4, 5, 6, 7,8];
console.log(array_values.length);
// 8 
array_values.length = 0;  
console.log(array_values.length);
// 0
console.log(array_values);
// []

11. Optional Chaining

The optional chaining ?. stops the evaluation if the value before ?. is undefined or null and returns undefined.

const user = {
  employee: {
    name: “Kapil”
  }
};
user.employee?.name;
// Output: “Kapil”
user.employ?.name;
// Output: undefined
user.employ.name
// Output: VM21616:1 Uncaught TypeError: Cannot read property ‘name’ of undefined

12. Arrow Functions

Although an arrow function expression is a more compact alternative to a traditional function expression, it has limitations and cannot be used in all situations. They refer to the environment in which they are defined because they have lexical scope (parental scope) and do not have their own this and arguments.

const person = {
name: ‘Kapil’,
sayName() {
    return this.name;
    }
}
person.sayName();
// Output
“Kapil”

However, 

const person = {
name: ‘Kapil’,
sayName : () => {
    return this.name;
    }
}
person.sayName();
// Output
“”

13. Rounding numbers

The toFixed() method converts a number rounding to a specified number of decimals.

var pi =3.1415;
pi = pi.toFixed(2);  // pi will be equal to 3.14

Note: toFixed() returns a string and not a number.

14. Quicker for loops compare to legacy onces

  • for and for..in gets you index by default, but you can use arr[index].
  • for..in accepts non numeric as well so avoid it.
  • forEach, for…of gets you an element directly.
  • forEach can get you an index also but for…of can’t.
  • for and for…of considers holes in array but other 2 do not.  

15. Ternary Operator is cool

You can avoid nested conditional if..elseif..elseif with ternary operators.

function Fever(temp) {
    return temp > 97 ? ‘Visit Doctor!’
      : temp < 97 ? ‘Go Out and Play!!’
      : temp === 97 ? ‘Take Some Rest!’;
}

// Output
Fever(97): “Take Some Rest!”
Fever(100): “Visit Doctor!”

Conclusion

In this article, we shared with you the top 15 tips for improving JavaScript performance. If you go ahead and implement all these changes, you will notice a significant improvement in the speed of your JavaScript web development and applications.

It may be difficult to remember all of these tips all at once, especially if you are working under a time constraint. If you require any additional assistance, please contact us. We hope you enjoyed this blog; please return to this space for more insightful content.

About Galaxy Weblinks

We specialize in delivering end-to-end software design & development services and have hands-on experience with popular front-end and back-end languages like JavaScript. Our back-end and front-end engineers also help in improving security, reliability, and features to make sure your business application scales and remain secure.

Share

Stay up to date with latest happenings in our space