Top 20 JavaScript tips and tricks to increase your Speed and Efficiency

These are simple and effective ways to speed up your development work and reduce code lines!

We are often asked to write functions like sorting, searching, passing parameters, swapping value, and finding unique values.

JavaScript is a great language to learn and use. There are many ways to solve the same problem. We will only discuss the fastest ones in this article.

These methods will help you in many ways:

  • Reduce the number of LOC (lines of code)
  • Code Competitions
  • Hackathons
  • Other tasks that are time-bound

Most of these JavaScript Hacks uses techniques from ECMAScript6(ES2015) onwards, though the latest version is ECMAScript11(ES2020).

Note : All the below tricks were tested using Google Chrome’s Console.

1. Declare and Initialize Arrays

You can use default values such as “”, null, or 0. to initialize an array of a particular size. These values can be used to initialize an array of a particular size with default values like “”, null or 0.

const array = Array(5).fill(''); 
// Output 
(5) ["", "", "", "", ""]

const matrix = Array(5).fill(0).map(()=>Array(5).fill(0)); 
// Output
(5) [Array(5), Array(5), Array(5), Array(5), Array(5)]
0: (5) [0, 0, 0, 0, 0]
1: (5) [0, 0, 0, 0, 0]
2: (5) [0, 0, 0, 0, 0]
3: (5) [0, 0, 0, 0, 0]
4: (5) [0, 0, 0, 0, 0]
length: 5

2. Find out the sum, minimum and maximum value

To quickly find basic math operations, we should use reduce.

const array  = [5,4,7,8,9,2];
  • Sum
array.reduce((a,b) => a+b);
// Output: 35
  • Max
array.reduce((a,b) => a>b?a:b);
// Output: 9
  • Min
array.reduce((a,b) => a<b?a:b);
// Output: 2

3. Sorting an array of strings, numbers or objects

There are inbuilt methods to sort strings, such as reverse() and sort(). But what about numbers and arrays of objects? Let’s look at sorting hacks that can be used for both Numbers and Objects in Increasing or Decreasing order.

  • Sort String Array
const stringArr = ["Joe", "Kapil", "Steve", "Musk"]
stringArr.sort()
// Output
(4) ["Joe", "Kapil", "Musk", "Steve"]

stringArr.reverse()
// Output
(4) ["Steve", "Musk", "Kapil", "Joe"]
__S.12__
  • Sort Number Array
const array = [40.100, 1, 5, 25, 10,];
array.sort(a,b). => a–b
// Output
(6) [1, 5, 10, 25, 40, 100]

array.sort((a.b) => (b-a);
// Output
(6) [100-40, 25, 10, 5, 1,]
__S.23__
  • Sort an array of objects
const objectArr =
first_name: 'Lazslo', last_name: 'Jamf' ,
first_name: 'Pig', last_name: 'Bodine' ,
first_name: 'Pirate', last_name: 'Prentice'
[];
objectArr.sort((a, b) => a.last_name.localeCompare(b.last_name));
// Output
(3) [{}, {}]
0: first_name: "Pig", last_name: "Bodine"
1: first_name: "Lazslo", last_name: "Jamf"
2: first_name: "Pirate", last_name: "Prentice"
Länge: 3
__S.38__

4. Do you ever need to filter out false values from an array?

You can easily omit false values such as 0, undefined null, false, or “”, by using the below trick

const array = [3,0, 6, 7, ''?, false]
array.filter(Boolean);
// Output
(3) [3, 6, 7, 7]
__S.47__

5. Use Logical Operators to deal with various conditions

You can use basic of logical operator OR to reduce nested If..else cases or switch cases.

function doSomething(arg1){function doSomething (arg1)
10;
// Set arg1-10 as the default, if it isn't already.
Return arg1
}

let foo = 10;
foo ===10 && doSomething()
// is the same as "foo == 10") then doSomething()
// Output: 10.

doSomething();
// is the same as "foo!= 5" then doSomething()
// Output: 10.
__S.66__

6. Get rid of duplicates

Perhaps you have used indexOf() in conjunction with for loop to return the first index found or the newer includes(), which returns boolean true/false of an array to remove duplicates. These are two faster approaches.

const array = [5,4,7.8,9,2,7.5,]
array.filter((item,idx,arr) => arr.indexOf(item) === idx);
//
const nonUnique = [...new Set(array)];
// Output: (5, 4, 7, 8, 9, 2, 2)
__S.77__

7. Create a Counter Object, or Map

Most of the time, the requirement to solve problem by creating counter object or map which tracks variables as keys with their frequency/occurrences as values.

let string = "kapilalipak"

={}; Const Table
for(let char of string) {For(let char string)
table[char]=table[char]+1 || 1;
}
// Output
k. 2, a. 3, p. 2, i. 2, l. 2
__S.90__

And

const countMap = New Map()
for (let i = 0; i < string.length; i++) {
if (countMap.has(string[i])) {
countMap.set(string[i], countMap.get(string[i]) + 1);
} else {or else
countMap.set(string[i], 1);
}
}
// Output
Map(5) "k” => 2, “a” => 3, “p” => 2, „i” => 2, „l” => 2
__S.103__

8. Cool Ternary Operator

If..elseif..elseif can be avoided by using ternary operators.

function Fever(temp) {Function Fever(temp).
Return temp > 97? "Visit Doctor!"
Temp 97 "Go out and play!"
Temp ===97 "Take some rest!" 'Take Some Rest!
}

// Output
Fever (97): "Take Some Recover!"
Fever (100): "Visit Doctor!" "

9. Loops are quicker than legacy onces

  • for, and to..in get you index by default. But you can also use arr[index].
  • for..in also accepts numeric characters so you can avoid them.
  • forEachfor...of gets you element directly.
  • forEach can get you index also but for...of can’t.
  • for and for...of considers holes in array but other 2 do not.

10. Combine 2 objects

In our daily lives, we often need to combine multiple objects.

const user = {const user =
name: 'Kapil Raghuwanshi',
gender: 'Male'
;
const college = {const college =
Primary: "Mani Primary School"
Secondary: 'Lass Secondary School
;
const skills = {
Programming: 'Extreme,'
Swimming: The 'Average'
Sleeping: "Pro"
;

const summary = {

// Output
gender: "Male"
name: "Kapil Raghuwanshi"
primary: "Mani Primary Schools"
Programming: "Extreme."
Secondary: "Lass Secondary School."
Sleeping: Pro
Swimming: "Average."
__S.34__

11. Arrow Functions

An arrow function expression can be used as a compact alternative for a traditional function expression. However, it is not suitable for all situations. They have lexical scope (parental) and do not have their own arguments, so they refer to the environment they are used in.

const person = {const person =
Name: "Kapil",
sayName() {SayName()
Return this.name
}
}
person.sayName()
// Output
"Kapil"
__S.49__

But

const person = {const person =
Name: "Kapil",
sayName : () => {SayName: ()=>
Return this.name
}
}
person.sayName()
// Output
""
__S.61__

12. Optional Chaining

Optional chaining?. If the value is before?, the evaluation stops. is null or undefined, and returns undefined.

const user = {const user =
employee: {
Name: "Kapil
}
;
user.employee.name
// Output: Kapil
user.employ.name
// Output: undefined
user.employ.name
// Output: VM21616.1 Uncaught TypeError
__S.79__

13. Shuffle an Array

Making use of inbuilt Math.random() method.

const list = [1,2, 3, 4, 5, 6, 7, 7, 8, 9,]
list.sort(() => {List.sort() =>
Return Math.random() – 0.5
;
// Output
(9) [2, 5,1, 6, 9, 8, 4, 3, 7,]
// Recall it!
(9) [4, 1, 5, 3, 8, 2, 9, 6,]
_

14. Nullish Coalescing Operator

The (??)nullish coalescing operator The nullish coalescing operator (??) is a logical operand that returns its right hand side operand if its left-hand operand is null, undefined, or both. It also returns its left side operand otherwise.

const foo = null 'my school';
// Output: "my school"

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

15. Rest & Spread operators

The 3 mysterious dots... are able to rest or spread!

function myFun(a,  b, ...manyMoreArgs) {
   return arguments.length;
}
myFun("one", "two", "three", "four", "five", "six");

// Output: 6

And

const parts = ['shoulders', 'knees']; 
const lyrics = ['head', ...parts, 'and', 'toes']; 

lyrics;
// Output: 
(5) ["head", "shoulders", "knees", "and", "toes"]

16. Default Parameters

const search = (arr, low=0,high=arr.length-1) => {
    return high;
}
search([1,2,3,4,5]);

// Output: 4

17. Convert Decimal to Binary or Hexa

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

const num = 10;

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

18. Simple Swap 2 values using Destructuring

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

[a,b]

// Output (2) [8, 5]

19. Single-liner Palindrome check

This isn’t a trick in itself, but it will help you get started with strings.

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

20. Turn Object attributes into an Array of attributes

Using Object.entries(),Object.keys() and Object.values()

const obj = { a: 1, b: 2, c: 3 };

Object.entries(obj);
// Output
(3) [Array(2), Array(2), Array(2)]
0: (2) ["a", 1]
1: (2) ["b", 2]
2: (2) ["c", 3]
length: 3

Object.keys(obj);
(3) ["a", "b", "c"]

Object.values(obj);
(3) [1, 2, 3]

If you learned something useful from this article, or it made your development work more efficient, please save it and share with your colleagues.

Also Check:

Happy Learning …☺️

About us: Codelivly is a platform designed to help newbie developer to find the proper guide and connect to training from basics to advance .

9 thoughts on “Top 20 JavaScript tips and tricks to increase your Speed and Efficiency”

  1. I really like your blog.. very nice colors & theme.
    Did you make this website yourself or did you hire someone to do it for you?
    Plz answer back as I’m looking to construct my own blog
    and would like to find out where u got this from. thanks

    Reply
  2. Hi, I do believe this is a great blog. I stumbledupon it 😉 I will return once again since i have saved as
    a favorite it. Money and freedom is the best way to change, may you be rich and continue to help others.

    Reply
  3. Excellent beat ! I would like to apprentice at the same time as you amend your web site, how could i subscribe for a weblog website?

    The account aided me a applicable deal. I had
    been tiny bit acquainted of this your broadcast offered brilliant transparent idea

    Reply
  4. Wonderful blog! I found it while browsing on Yahoo News.

    Do you have any tips on how to get listed in Yahoo
    News? I’ve been trying for a while but I never seem to get there!
    Thanks

    Reply
  5. Appreciating the persistence you put into your site and detailed information you provide.
    It’s nice to come across a blog every once in a
    while that isn’t the same old rehashed information. Fantastic read!
    I’ve saved your site and I’m adding your RSS feeds to my Google account.

    Reply

Leave a Comment