We often write JavaScript code, but how do we write clean and maintainable code? This article will explain 17 JavaScript code techniques to help you improve your programming skills, plus help you prepare for your JavaScript interview in 2021.

(Note that I will put the bad code at the top with //longhand and the good code at the bottom with // dictate for comparison)

1. If there are multiple conditions

Sometimes you’ll find cases where a variable is equal to more than one value:

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

if else? It’s better to use 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 simply use
let test = x > 10;
console.log(test);
Copy the code

Ternary operators can also be nested, as follows:

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

However, nesting too many layers is not recommended.

3. Null, Undefined, Null check

How can I tell if there is a blank value in front?

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

4. Null Value Checks and assigns default values

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

5. Undefined checks and assigns default values

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

6. The foreach loop

How to iterate better?

// Longhand for (var i = 0; i < testData.length; I ++) // Dictate for (let I in testData)Copy the code

Let I in or let I of is a better way to say,

Or: Use forEach

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


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

7. Comparison returns

Using comparisons in return statements will avoid our 5 lines of code and reduce them to 1.

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

8. Simple way to call a function

Resolve function calls with ternary operators

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

9. Switch

Switch is sometimes too long? Let’s see if we can optimize

// 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[anything] && data[anything]();
Copy the code

10. Multiline string shorthand

How to handle strings with multiple lines? With + number?

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

11.Implicit Return Shorthand

There is an implicit return when using the clipping function, note the parentheses.

Longhand:
//longhand
function getArea(diameter) {
  return Math.PI * diameter
}



//shorthand
getArea = diameter => (
  Math.PI * diameter;
)
Copy the code

12.Lookup Conditions 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 we have a better way 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

13.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

14. Object.values()

This is also a new feature introduced in ES8 that performs similar functionality to Object.Entry (), 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

15. Repeating the 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?

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

Exponential power functions

Shorthand for mathematical exponential power functions:

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

17. Numeric delimiters

Now, you can easily separate numbers just by using _.

//old syntax
let number = 98234567



//new syntax
let number = 98_234_567
Copy the code

conclusion

We can improve our programming skills by thinking and taking notes as we write code to see which is the best and shortest way.

Other highlights

  • 8 React Libraries you should Try in 2021

  • CURD API with Node, Sequelize, Postgres, and Docker

  • 5 libraries you’ll use for the React project in 2021

  • Every Web developer must have 15 VSCode extensions by 2021

  • 73 NPM packages to improve productivity