This article is from the huawei Cloud community “20 JavaScript Tips and Tricks to Improve Code Efficiency” by Hai Yong.

In our daily tasks, we write functions like sorting, searching, finding unique values, passing parameters, swapping values, etc., so here I have a list of my shorthand tips! ✌ 🏻

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

These methods will certainly help you:

  • Reduce the number of LOCs (lines of code),
  • Coding contests,
  • hackathon
  • Or other time-limited tasks. ⏱

Most of these JavaScript Hacks use technologies later than 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 use default values (such as “”, NULL, or) to initialize array 0 of a specific size. You might have used these for one-dimensional arrays, but how do you initialize a two-dimensional array/matrix?

const array = Array(5).fill(''); / / output (5) (" ", ""," ", ""," "] const matrix = Array (5). The fill (0). The map (() = > Array (5). The 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: 5Copy the code

2. Find the sum, minimum, and maximum

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

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

3. Sort strings, numbers, or object arrays

We have built-in methods sort() and reverse() for sorting strings, but what about numbers or arrays of objects?

Let’s look at 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. The reverse (); // Output (4) ["Steve", "Musk", "Kapil", "Joe"]Copy the code
  • 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. The sort ((a, b) = > b - a); // Output (6) [100, 40, 25, 10, 5, 1]Copy the code
  • Object array sort
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: 3Copy the code

4. Filter out false values from the array

Falsy values like 0, undefined, null, false, “”, “” can be easily omitted by using the following method

const array = [3, 0, 6, 7, '', false]; array.filter(Boolean); // Output (3) [3, 6, 7]Copy the code

5. Use logical operators for various conditions

If you want to reduce nesting if… Else OR switch case, you can simply use the basic logical operators AND/OR.

function doSomething(arg1){ arg1 = arg1 || 10; // If not set, arg1 is set to 10 as the default value 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: 10Copy the code

6. Delete the duplicate value

You may already be using indexOf() with a for loop that returns the first index found or a newer includes() that returns a Boolean true/false from an array to find/remove duplicates. So we have two faster ways of doing this.

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

7. Create a counter object or map

In most cases, you need to solve the problem by creating a counter object or map that tracks a variable as a key and its frequency/occurrence as a value.

let string = 'kapilalipak'; const table={}; for(let char of string) { table[char]=table[char]+1 || 1; } {k: 2, a: 3, p: 2, I: 2, l: 2}Copy the code

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}Copy the code

8. Ternary operators are cool

You can avoid using ternary operators to nest conditions if… Elseif… Elseif.

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!"Copy the code

9. The for loop is faster than the old version

  • forandfor.. inYou are provided with an index by default, but you can use arR [index].
  • for.. inAlso accept non-numbers, so avoid it.
  • forEach.for... ofGet the element directly.
  • forEachCan also provide you with an index, butfor... ofCan’t.
  • forandfor... ofConsider the holes in the array, but not the other two.

10. Merge two objects

Often we need to merge multiple objects in our 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}; Gender: "Male" name: "Kapil Raghuwanshi" Primary: "Mani Primary School" Programming: "Extreme" secondary: "Lass Secondary School" sleeping: "Pro" swimming: "Average"Copy the code

11. Arrow function

Arrow function expressions are compact alternatives to traditional function expressions, but have limitations and cannot be used in all situations. Since they have lexical scope (parent scope) and have no scope of their own this, arguments therefore refer to the context in which they are defined.

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

but

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

12. Optional link chain

Optional links? . If the value is in? Before, it stops evaluating. Is undefined or null and returns

Undefined. const user = { employee: { name: "Kapil" } }; user.employee? .name; // Output: "Kapil" user. .name; // Output: undefined user.develop. name // Output: vm21616:1 Uncaught TypeError: Cannot read property 'name' of undefinedCopy the code

13. Scramble arrays

Utilize 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]Copy the code

14. Empty merge operator

Null merge operator (??) Is a logical operator that returns its right-hand operand if its left-hand operand is empty or undefined, otherwise returns its left-hand operand.

const foo = null ?? 'my school'; // output: "my school" const baz = 0? 42. // Output: 0Copy the code

15. Rest & Spread operators

Those mysterious 3 points… Can rest or spread! 🤓

function myFun(a, b, ... manyMoreArgs) { return arguments.length; } myFun("one", "two", "three", "four", "five", "six"); // Output: 6Copy the code

and

const parts = ['shoulders', 'knees']; const lyrics = ['head', ...parts, 'and', 'toes']; lyrics; / / output: (5) [" head ", "shoulders", "knees", "and", "toes"]Copy the code

16. Default parameters

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

Convert decimal to binary or hexadecimal

We can use some built-in methods, such as.toprecision () or.tofixed (), to implement many of the help functions while solving the problem.

const num = 10; num.toString(2); // Output: "1010" num. ToString (16); // Output: "a" num. ToString (8); // output: "12"Copy the code

18. Use deconstruction to simply swap two values

let a = 5; let b = 8; [a,b] = [b,a] [a,b]Copy the code

19. One-line palindrome check

Well, it’s not an overall shorthand technique, but it will give you a clear idea of how to use strings.

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

20. Convert the Object property into an array of properties

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: [" a ", 1) (2) : 1 (2) (" b ", 2) 2: (2) (" c ", 3) length: 3 Object. Keys (obj); (3) ["a", "b", "c"] Object.values(obj); (3) [1, 2, 3]Copy the code

Click to follow, the first time to learn about Huawei cloud fresh technology ~