How to write code is not so "dish"

1. If there are multiple conditions

We can store multiple values in an array and 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
}

2. If true... Otherwise abbreviated

This is a big shortcut when we have an if else condition that does not contain larger logic. We can simply use the ternary operator to implement this abbreviation.

// 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);

When we have nested conditions, we can use this method.

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

3. Declare variables

This shorthand form can be used when we want to declare two variables that have a common value or type.

//Longhand 
let test1;
let test2 = 1;

//Shorthand 
let test1, test2 = 1;

4.Null, Undefined, null check

When we create a new variable, sometimes we want to check whether the value of the variable we refer to is empty or undefined. JavaScript does have a very good shorthand tool to implement these functions.

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

// Shorthand
let test2 = test1 || '';

5.null value checking and assigning default values

let test1 = null,
    test2 = test1 || '';

console.log("null check", test2); // output will be ""

6.undefined value check and assign default values

let test1 = undefined,
    test2 = test1 || '';

console.log("undefined check", test2); // output will be ""

Normal value check

let test1 = 'test',
    test2 = test1 || '';

console.log(test2); // output: 'test'

7. Assign values to multiple variables

This shorthand technique is useful when we work 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];

8. Abbreviation of assignment operator

We deal with many arithmetic operators in programming, which 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;

9. If abbreviations exist

This is one of the common abbreviations we all use, but it is still worth mentioning.

// Longhand
if (test1 === true) or if (test1 !== "") or if (test1 !== null)

// Shorthand //it will check empty string,null and undefined too
if (test1)

Note: if test1 has any value, it will enter logic after the if loop. This operator is mainly used for null or undefined checking.

10. AND (& &) operator for multiple conditions

If the function is called only when the variable is true, you can use the & & operator.

//Longhand 
if (test1) {
 callMethod(); 
} 

//Shorthand 
test1 && callMethod();

11.foreach loop abbreviation

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)

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

12. Comparison in return

We can also use comparison in the return statement. It will avoid our 5 lines of code and reduce them to 1 line.

// 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');
}

13. Arrow function

//Longhand 
function add(a, b) { 
   return a + b; 
} 

//Shorthand 
const add = (a, b) => a + b;

More examples.

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

14. Short function call

We can use ternary operators to achieve these functions.

// 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)();

15. Switch abbreviation

We can save conditions in key value objects and use them according to 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]();

16. Implicit return abbreviation

Using the arrow function, we can return the value directly without writing a return statement.

//longhand
function calculate(diameter) {
  return Math.PI * diameter
}

//shorthand
calculate = diameter => (
  Math.PI * diameter;
)

17. Decimal base index

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

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

18. Default parameter value

//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

19. Abbreviation of extension operator

//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]

For cloning, we can also use the extension operator.

//longhand

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

//shorthand

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

20. Template text

If you're tired of using + to connect multiple variables in a single string, this shorthand can eliminate your headache.

//longhand
const welcome = 'Hi ' + test1 + ' ' + test2 + '.'

//shorthand
const welcome = `Hi ${test1} ${test2}`;

21. Multiline string abbreviation

When dealing with multiline 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`

22. Object attribute assignment

let test1 = 'a'; 
let test2 = 'b';

//Longhand 
let obj = {test1: test1, test2: test2}; 

//Shorthand 
let obj = {test1, test2};

23. Convert string to number

//Longhand 
let test1 = parseInt('123'); 
let test2 = parseFloat('12.3'); 

//Shorthand 
let test1 = +'123'; 
let test2 = +'12.3';

24. Use deconstruction abbreviation

//longhand
const test1 = this.data.test1;
const test2 = this.data.test2;
const test2 = this.data.test3;

//shorthand
const { test1, test2, test3 } = this.data;

25. Abbreviated by Array.find

The find method is really useful when we do have an array of objects and we want to find a specific object 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' }

26. Abbreviation of search criteria

If we have code to check the type and call different methods according to the type needs, we can choose to use multiple else ifs or switch, but what if we have a better shorthand method than this?

// 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();

27. Bitwise index abbreviation

When we traverse the array to find a specific value, we do use the indexOf() method. What if we find a better method? 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
}

The bitwise (~) operator returns the true value of any value except - 1. Denying it is as simple as doing ~ ~. In addition, we can also use the include() function:

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

28.Object.entries()

This function helps to convert an object to 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' ]
]
**/

29.Object.values()

This is also a new function introduced in ES8. It performs functions similar to Object.entries(), but has no key parts:

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

30. Double digit abbreviation

Double NOT bitwise operator method (32-bit integers only)

// Longhand
Math.floor(1.9) === 1 // true

// Shorthand
~~1.9 === 1 // true

31. Repeat a string multiple times

To repeat the same characters over and over again, we can use the for loop and add them to the same loop, but what if we have 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);

32. Find the maximum and minimum values in the array

const arr = [1, 2, 3]; 
Math.max(...arr); // 3
Math.min(...arr); // 1

33. Get characters from string

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

34. Abbreviation of mathematical exponential power function

//longhand
Math.pow(2,3); // 8

//shorthand
2**3 // 8

Posted by tuurlijk on Mon, 22 Nov 2021 03:42:06 -0800