Today I Learned - Rocky Kev

TIL some ways to refactor your code

POSTED ON:

TAGS:

Shorthand tricks:

Shorthand for multiple OR (||) conditions.


// INSTEAD OF THIS:
if (fruit === 'apple' || fruit === 'orange' || fruit === 'banana' || fruit ==='grapes') {
//code
}

// DO THIS:
if (['apple', 'orange', 'banana', 'grapes'].includes(fruit)) {
//code
}

Shorthand for multiple AND conditions.


// INSTEAD OF THIS:
if(obj && obj.address && obj.address.postalCode) {
console.log(obj.address.postalCode)
}

// DO THIS: Use optional chaining
console.log(obj?.address?.postalCode);

Shorthand to check for null/undefined/empty or to set a default value


// INSTEAD OF THIS:
if (first !== null || first !== undefined || first !== '') {
let second = first;
}

// DO THIS:
const second = first || '';

Shorthand for replacing switch cases


// INSTEAD OF THIS
switch (number) {
case 1:
return 'one';
case 2:
return 'two';
default:
return;
}

// DO THIS:
const data = {
1: 'one',
2: 'two'
};


data[num]

Shorthand for calling functions conditionally


// INSTEAD OF THIS:

function area() {
console.log('area');
}

function volume() {
console.log('volume');
}

if( type === 'square' ) {
area();
} else {
volume();
}


// DO THIS:
(type === 'square' ? area : volume)()

Via
https://javascript.plainenglish.io/stop-writing-javascript-like-this-a7fafbe451a5


Related TILs

Tagged:

TIL what is npm Script

Despite their high usage they are not particularly well optimized and add about 400ms of overhead. In this article we were able to bring that down to ~22ms.

TIL fancy methods to transform Javascript Objects

You can use Object.entries(), Object.keys(), Object.fromEntries()...

TIL how to hide your JS code

ONE THING TO NOTE: Encrypting a script is stronger than obfuscation, both methods are still not adequate to protect secret content. Honestly, I don't think it's worth it on a production site, and instead just go with pure server-side if you want security. But it's fascinating.