34 JavaScript Optimization Techniques to know in 2021

 

Life as a developer is always learning new things, and keeping up with changes shouldn’t be any harder than it is now, my motivation is to introduce all the JavaScript best practices, such as shorthand and functionality, that we as front-end developers must know to make life easier in 2021

 

You may have been in JavaScript development for a long time, but sometimes you may not be using the latest features that solve problems without fixing them or writing some extra code. These techniques can help you write clean and optimized JavaScript code. In addition, these topics can help you prepare for your JavaScript interviews in 2021.

Here, I’ll offer a new series on shorthand techniques that can help you write cleaner and better JavaScript code. Here’s a cheat sheet of JavaScript coding you need to know in 2021.

1. If there are multiple conditions

We can store multiple values in an array, and we can use the array include method.

//longhand
if (x === 'abc' || x === 'def' || x === 'ghi' || x ==='jkl') {
    //logic
}
//shorthand
if (['abc', 'def', 'ghi', 'jkl'].includes(x)) {
   //logic
}
Copy the code

2. If true… The else shorthand

This is a bigger shortcut when we have if-else conditions that do not contain larger logic. We can implement this shorthand simply by using the ternary operator.

// Longhand
let test: boolean;
if (x > 100) {
    test = true;
} else {
    test = false;
}
// Shorthand
let test = (x > 10) ? true : false;
//or we can use directly
let test = x > 10;
console.log(test);
Copy the code

We can do this when we have nested conditions.

let x = 300,
test2 = (x > 100) ? 'greater 100' : (x < 50) ? 'less 50' : 'between 50 and 100';
console.log(test2); // "greater than 100"
Copy the code

3. Declare variables

We use this shorthand when we want to declare two variables that have a common value or a common type.

//Longhand 
let test1;
let test2 = 1;
//Shorthand 
let test1, test2 = 1;
Copy the code

4. Empty, undefined, empty check

When we do create a new variable, sometimes we want to check that the variable referenced for its value is null or undefined. JavaScript does have very good shortcuts to these things.

// Longhand if (test1 ! == null || test1 ! == undefined || test1 ! == '') { let test2 = test1; } // Shorthand let test2 = test1 || '';Copy the code

5. Null check and assign defaults

let test1 = null,
    test2 = test1 || '';
console.log("null check", test2); // output will be ""
Copy the code

6. Undefined values check and assign defaults

let test1 = undefined,
    test2 = test1 || '';
console.log("undefined check", test2); // output will be ""
Copy the code

Normal value examination

let test1 = 'test',
    test2 = test1 || '';
console.log(test2); // output: 'test'
Copy the code

Bonus: now we can use theme 4,5 and 6? The operator)

The void merge operator

Null merge operator?? If the left side is null or undefined, the value on the right side is returned. By default, it returns the value on the left.

const test= null ?? 'default';
console.log(test);
// expected output: "default"const test1 = 0 ?? 2;
console.log(test1);
// expected output: 0
Copy the code

7. Assign values to multiple variables

This shorthand technique is useful when we are dealing with multiple variables and want to assign different values to different variables.

//Longhand 
let test1, test2, test3;
test1 = 1;
test2 = 2;
test3 = 3;
//Shorthand 
let [test1, test2, test3] = [1, 2, 3];
Copy the code

8. Shorthand for the assignment operator

We deal with a lot of arithmetic operators in our programming. This is one of the useful techniques for assigning operators to JavaScript variables.

// Longhand
test1 = test1 + 1;
test2 = test2 - 1;
test3 = test3 * 20;
// Shorthand
test1++;
test2--;
test3 *= 20;
Copy the code

9. If shorthand exists

This is one of the most common forms of shorthand that we all use, but it’s still worth mentioning.

// Longhand
if (test1 === true)

// Shorthand
if (test1)
Copy the code

Note: If test1 has any value, it will enter logic after the if loop, which is usually used for null or undefined checks.

10. Multiple conditional AND (&&) operators

The && operator can be used if the function is called only if the variable is true.

//Longhand 
if (test1) {
 callMethod(); 
} 
//Shorthand 
test1 && callMethod();
Copy the code

11. Foreach loop shorthand

This is one of the common shorthand techniques for iteration.

// Longhand
for (var i = 0; i < testData.length; i++)

// Shorthand
for (let i in testData) or  for (let i of testData)
Copy the code

An array of each variable

function testData(element, index, array) {
  console.log('test[' + index + '] = ' + element);
}

[11, 24, 32].forEach(testData);
// logs: test[0] = 11, test[1] = 24, test[2] = 32
Copy the code

12. Compare the return values

We can also use comparisons in return statements. It will avoid our five lines of code and reduce them to one.

// Longhand let test; function checkReturn() { if (! (test === undefined)) { return test; } else { return callMe('test'); } } var data = checkReturn(); console.log(data); //output test function callMe(val) { console.log(val); } // Shorthand function checkReturn() { return test || callMe('test'); }Copy the code

Arrow function

//Longhand 
function add(a, b) { 
   return a + b; 
} 
//Shorthand 
const add = (a, b) => a + b;
Copy the code

More examples.

function callMe(name) {
  console.log('Hello', name);
}
callMe = name => console.log('Hello', name);
Copy the code

14. Short function calls

We can use ternary operators to do this.

// Longhand
function test1() {
  console.log('test1');
};
function test2() {
  console.log('test2');
};
var test3 = 1;
if (test3 == 1) {
  test1();
} else {
  test2();
}
// Shorthand
(test3 === 1? test1:test2)();
Copy the code

15. The Switch shorthand

We can store conditions in key-value objects and use them based on conditions.

// Longhand
switch (data) {
  case 1:
    test1();
  break;

  case 2:
    test2();
  break;

  case 3:
    test();
  break;
  // And so on...
}

// Shorthand
var data = {
  1: test1,
  2: test2,
  3: test
};

data[something] && data[something]();
Copy the code

16. Implicit return of shorthand

Using the arrow function, we can return values directly without having to write a return statement.

//longhand
function calculate(diameter) {
  return Math.PI * diameter
}
//shorthand
calculate = diameter => (
  Math.PI * diameter;
)
Copy the code

17. Decimal base exponent

// Longhand
for (var i = 0; i < 10000; i++) { ... }

// Shorthand
for (var i = 0; i < 1e4; i++) {
Copy the code

18. Default parameter values

//Longhand
function add(test1, test2) {
  if (test1 === undefined)
    test1 = 1;
  if (test2 === undefined)
    test2 = 2;
  return test1 + test2;
}
//shorthand
add = (test1 = 1, test2 = 2) => (test1 + test2);
add() //output: 3
Copy the code

19. Point difference operator shorthand

//longhand // joining arrays using concat const data = [1, 2, 3]; const test = [4 ,5 , 6].concat(data); //shorthand // joining arrays const data = [1, 2, 3]; const test = [4 ,5 , 6, ...data]; console.log(test); // [4, 5, 6, 1, 2, 3]Copy the code

For cloning, we can also use propagation operators.

//longhand

// cloning arrays
const test1 = [1, 2, 3];
const test2 = test1.slice()
//shorthand

// cloning arrays
const test1 = [1, 2, 3];
const test2 = [...test1];
Copy the code

20. Template text

If you’re tired of using + to concatenate multiple variables in a single string, this shorthand will eliminate your headache.

//longhand
const welcome = 'Hi ' + test1 + ' ' + test2 + '.'
//shorthand
const welcome = `Hi ${test1} ${test2}`;
Copy the code

21. Multiline string shorthand

When working with multi-line strings in code, we can use the following functions:

//longhand
const data = 'abc abc abc abc abc abc\n\t'
    + 'test test,test test test test\n\t'
//shorthand
const data = `abc abc abc abc abc abc
         test test,test test test test`
Copy the code

22. Object attribute allocation

let test1 = 'a'; 
let test2 = 'b';
//Longhand 
let obj = {test1: test1, test2: test2}; 
//Shorthand 
let obj = {test1, test2};
Copy the code

23. The string is a number

//Longhand let test1 = parseInt('123'); Let test2 = parseFloat (' 12.3 '); //Shorthand let test1 = +'123'; Let test2 = + '12.3';Copy the code

24. Assign shorthand

//longhand
const test1 = this.data.test1;
const test2 = this.data.test2;
const test2 = this.data.test3;
//shorthand
const { test1, test2, test3 } = this.data;
Copy the code

25. Short for array. find

The find method is really useful when we do have an array of objects and we want to look up specific objects based on object properties.

const data = [{
        type: 'test1',
        name: 'abc'
    },
    {
        type: 'test2',
        name: 'cde'
    },
    {
        type: 'test1',
        name: 'fgh'
    },
]
function findtest1(name) {
    for (let i = 0; i < data.length; ++i) {
        if (data[i].type === 'test1' && data[i].name === name) {
            return data[i];
        }
    }
}
//Shorthand
filteredData = data.find(data => data.type === 'test1' && data.name === 'fgh');
console.log(filteredData); // { type: 'test1', name: 'fgh' }
Copy the code

26. Look up conditional shorthand

If we have code to check the type and need to call different methods based on the type, we can choose to use multiple else Ifs or switch, but what if our shorthand is better than that?

// Longhand if (type === 'test1') { test1(); } else if (type === 'test2') { test2(); } else if (type === 'test3') { test3(); } else if (type === 'test4') { test4(); } else { throw new Error('Invalid value ' + type); } // Shorthand var types = { test1: test1, test2: test2, test3: test3, test4: test4 }; var func = types[type]; (! func) && throw new Error('Invalid value ' + type); func();Copy the code

27. Shorthand bitwise index

We do use the indexOf () method when we iterate over an array to find a particular value, but what if we found a better one? Let’s look at this example.

//longhand if(arr.indexOf(item) > -1) { // item found } if(arr.indexOf(item) === -1) { // item not found } //shorthand if(~arr.indexOf(item)) { // item found } if(! ~arr.indexOf(item)) { // item not found }Copy the code

The bitwise (~) operator returns a true value that is not -1. Inverse is like doing! As simple as ~. Alternatively, we can use the include () function:

if (arr.includes(item)) { 
// true if the item found
}
Copy the code

28. Object. Entries ()

This feature helps to convert an object into an array of objects.

const data = { test1: 'abc', test2: 'cde', test3: 'efg' };
const arr = Object.entries(data);
console.log(arr);
/** Output:
[ [ 'test1', 'abc' ],
  [ 'test2', 'cde' ],
  [ 'test3', 'efg' ]
]
**/
Copy the code

29. The Object. The values ()

This is also a new feature introduced in ES8 that performs similar functionality to Object.entries (), but without the key parts:

const data = { test1: 'abc', test2: 'cde' };
const arr = Object.values(data);
console.log(arr);
/** Output:
[ 'abc', 'cde']
**/
Copy the code

30. Double Bitwise

(The dual NOT bitwise operator method only works with 32-bit integers.)

// Longhand Math.floor(1.9) === 1 // true // Sleep ~~1.9 === 1 // trueCopy the code

31. Repeat a string multiple times

To repeat the same characters over and over again, we could use a for loop and add them to the same loop, but what if we had a shorthand method?

//longhand 
let test = ''; 
for(let i = 0; i < 5; i ++) { 
  test += 'test '; 
} 
console.log(str); // test test test test test 
//shorthand 
'test '.repeat(5);
Copy the code

32. Find the maximum and minimum values in the array

const arr = [1, 2, 3]; Math. Max (... arr); / / 3 Math. Min (... arr); / / 1Copy the code

33. Get characters from strings

let str = 'abc';
//Longhand 
str.charAt(2); // c
//Shorthand 
Note: If we know the index of the array then we can directly use index insted of character.If we are not sure about index it can throw undefined
str[2]; // c
Copy the code

34. Power shorthand

Short for exponential power functions in mathematics:

/ / longhand math.h pow (2, 3); // 8 //shorthand 2**3 // 8Copy the code

 

If you want to see the latest features of the JavaScript version, check out the following:

ES2021 / ES12

· replaceAll () : Returns a new string in which all pattern matches are replaced by the new replacement word.

· Promise.any () : It requires an iterable of the Promise object and returns a single Promise with a value when a Promise is fulfilled.

· Weak reference: This object holds a weak reference to another object without preventing that object from being garbage collected.

· FinalizationRegistry: Lets you request a callback when an object is garbage collected.

· Private visibility modifiers for methods and accessors: Private methods can be declared with #.

Logical operators: && and | | operators.

· Number separator: Enable underscores as separators in numeric text to improve readability.

· Intl.listFormat: This object enables language-sensitive list formats.

· Intl.dateTimeFormat: This object enables language-sensitive date and time formats.

ES2020 / ES11

BigInt: provides a way to represent (whole) numbers greater than 253 — 1

11. Dynamic import: Dynamic import provides the option to dynamically import JS files as modules. This will help you get modules on demand.

12. Null merge operator: Returns the value on the right if the left side is null or undefined. By default, it returns the value on the left.

GlobalThis: contains the globalThis value, which is basically used as a global object.

1. Promise.allsettled () : Returns a Promise that basically contains an array of objects with the results of each Promise.

15. Optional link: Read the value using any connected object or check method and check if the property exists.

1. String. Prototype. MatchAll () : returns all matches the regular expression String result of iterators.

17. Named Exports: With this feature, you can have multiple named exports per file.

18. Define a clear sequence:

1. Import.meta: Objects expose context-specific metadata to JS modules

ES2019 / ES10

1. Array.flat () : Create a new Array by combining other arrays in the main Array. Note: We can set the depth of the merged array.

1. Array. flatMap: Create a new Array by applying a callback function to each element of the Array.

1. Object.fromentries () : Converts the list of key-value pairs to objects.

1. String.trimstart () and String.trimend () : methods remove Spaces from the beginning and end of the String.

1. Try… Catch: The statement marks the block of statements to try, and if any errors occur, the catch will process them.

1. Function.tostring () : Converts any method/code to a string.

1. Symbol. Prototype. Description: return to Symbol the optional description of the object.

ES2018 / ES9

27. Asynchronous Iteration: With async and await, we can now run a series of asynchronous iterations in a for loop.

1. Promise.finally () : Return the Promise on settlement or rejection. This will help avoid duplication and capture handlers.

1. Rest/Spread property: used for object decomposition and arrays.

30. Regular expression named capture groups: can symbols be used after square brackets? Let’s name it.

31. Regular expression S (dotAll) flag: Matches any single character except carriage return. The S flag changes this behavior, thus allowing line terminators

32. Regular expression Unicode attribute escapes: this can be done by setting the Unicode U flag and p {… } and {p… } to set the Unicode property escape.

ES2017 / ES8

1.object.entries () : Returns an array of key and value pairs for the given Object.

1.object.values () : Returns an array of property values for a given Object.

1. PadStart () : Fills the current string with another string until the resulting string reaches its length.

1. PadEnd () : Padding the current string with the given string, starting at the end of the current string.

1. Object. GetOwnPropertyDescriptors () : returns the given Object all his property descriptors.

38. Asynchronous features: Extended on Promises to make asynchronous calls.

ES2016 / ES7

1. Array.prototype.includes () : Determines whether an Array includes a value in a given value. It returns true or false.

40. Exponentiation: Returns the result of raising the first operand to a power of the second operand.

ES2015 / ES6

41. Arrow function expressions: Substitute for traditional function expressions under certain circumstances

42. Enhanced object literals: Extended to support setting object constructs.

43. Classes: Create classes using the class keyword.

44. Template literals: You can add parameters directly to a string using ${param}

45. Deconstructing allocation: Helps extract values from arrays or properties from objects.

46. Default + Rest + Spread: The Default value is supported, with the Spread parameter or array as the parameter.

47. Let + Const:

48. Promises: Promises for asynchronous operation.

49. The module:

50. Map + Set + WeakMap + WeakSet:

51. Math + Number + String + Array + object API: