20 JavaScript tips and tricks to improve code efficiency

Posted by trace on Mon, 31 Jan 2022 06:32:00 +0100

Convenient and practical technology that can reduce the number of lines of code and speed up the development work!


In our daily tasks, we will write functions such as sorting, searching, finding unique values, passing parameters, exchanging values and so on, so here I list my shorthand skills! ✌🏻

JavaScript is really a great language 💛, It is worth learning and using. For a given problem, there can be more than one way to achieve the same solution. In this article, we will only discuss the fastest. 🚀

These methods will certainly help you:

  • Reduce the number of LOC (lines of code),
  • Coding competition,
  • Hacker Marathon
  • Or other time limited tasks. ⏱

Most of these JavaScript Hacks use technology after ECMAScript6(ES2015), although the latest version is ECMAScript11(ES2020).

Note: all of the following tips have been tested on the Google Chrome console.

1. Declare and initialize arrays

We can initialize an array 0 of a specific size with default values such as' ', null, or. You may have used these for one-dimensional arrays, but how do you initialize two-dimensional arrays / matrices?

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 the sum, minimum and maximum

We should use the reduce method to quickly find the basic mathematical operations.

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

3. Sort strings, numbers, or arrays of objects

We have built-in methods sort() and reverse() to sort strings, but what about numbers or object arrays?

Let's look at the ascending and descending sorting techniques for numbers and objects.

  • 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"]
  • Sort numeric 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]
  • Object array sorting
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"}
length: 3

4. Filter out false values from the array

False values like 0, undefined, null, false, "", "" can be easily omitted by the following methods

const array = [3, 0, 6, 7, '', false];
array.filter(Boolean);
// output
(3) [3, 6, 7]

5. Use logical operators for various conditions

If you want to reduce nested if... else or switch case s, you can simply use the basic logical operator AND/OR.

function doSomething(arg1){ 
    arg1 = arg1 || 10; 
// If not already set, set arg1 to 10 as the default
return arg1;
}

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

foo === 5 || doSomething();
// is the same thing as if (foo != 5) then doSomething();
// Output: 10

6. Delete duplicate values

You may have used indexOf() with a for loop that returns the first index found or the newer includes() returns a Boolean value of true/false from the array to find / remove duplicates. This is that we have two faster ways.

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

7. Create counter object or map

In most cases, you need to solve the problem by creating a counter object or map that tracks variables as keys and their frequency / occurrences as values.

let string = 'kapilalipak';

const table={}; 
for(let char of string) {
  table[char]=table[char]+1 || 1;
}
// output
{k: 2, a: 3, p: 2, i: 2, l: 2}

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 {
      countMap.set(string[i], 1);
    }
  }
// output
Map(5) {"k" => 2, "a" => 3, "p" => 2, "i" => 2, "l" => 2}

8. Ternary operators are cool

You can avoid using ternary operators to nest conditional if... Else if... Else if.

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!"

9. Compared with the old version, the for loop is faster

  • For and for In provides you with an index by default, but you can use arr[index].
  • for..in also accepts non numbers, so avoid it.
  • forEach,for...of gets the element directly.
  • forEach can also provide you with an index, but for Of can't.
  • For and for Of considers the holes in the array, but the other 2 do not.

10. Merge 2 objects

Usually we need to merge multiple objects in daily tasks.

const user = { 
 name: 'Kapil Raghuwanshi', 
 gender: 'Male' 
 };
const college = { 
 primary: 'Mani Primary School', 
 secondary: 'Lass Secondary School' 
 };
const skills = { 
 programming: 'Extreme', 
 swimming: 'Average', 
 sleeping: 'Pro' 
 };

const summary = {...user, ...college, ...skills};

// output
gender: "Male"
name: "Kapil Raghuwanshi"
primary: "Mani Primary School"
programming: "Extreme"
secondary: "Lass Secondary School"
sleeping: "Pro"
swimming: "Average"

11. Arrow function

Arrow function expression is a compact alternative to traditional function expression, but it has limitations and can not be used in all cases. Because they have a lexical scope (parent scope) and do not have their own scope this, arguments, they refer to the environment in which they are defined.

const person = {
name: 'Kapil',
sayName() {
    return this.name;
    }
}
person.sayName();
// output
"Kapil"

but

const person = {
name: 'Kapil',
sayName : () => {
    return this.name;
    }
}
person.sayName();
// output
""

12. Optional chain

Optional link If the value is? Before, stop the evaluation. 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

13. Disrupt the array

Use the built-in 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]

14. Empty merge operator

Empty merge operator (?) Is a logical operator that returns its right operand when its left operand is empty or undefined, otherwise returns its left operand.

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

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

15. Rest & spread operator

Those mysterious three points Can 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 hexadecimal

While solving the problem, we can use some built-in methods, such as toPrecision() or toFixed() to implement many help functions.

const num = 10;

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

18. Use deconstruction to simply exchange two values

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

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

19. Single line palindrome check

Well, this is not an overall shorthand technique, but it will give you a clear understanding of how to use string music.

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

20. Convert the Object attribute into an attribute array

use 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 know more skills like the above, you can tell me in the comment area and we can learn together.

I have been writing a technical blog for a long time and mainly published through CSDN. This is my technical article / tutorial. I hope you will like it! More relevant articles and my contact information are here:

https://github.com/wanghao221

If you really learn something new from this article, or it really makes your programming faster than before, like it, collect it and share it with your friends. 🤗 Finally, don't forget ❤ or 📑 Support

Topics: Javascript