DEV Community

Simc Dev
Simc Dev

Posted on

Change your old methods for writing a JavaScript Code - Shorthand's for JavaScript Code

1. Shorthand for if with multiple OR(||) conditions

if (car === 'audi' || car === 'BMW' || car === 'Tesla') {
    //code
}
Enter fullscreen mode Exit fullscreen mode

In a traditional way, we used to write code in the above pattern. but instead of using multiple OR conditions we can simply use an array and includes. Check out the below example.

if (['audi', 'BMW', 'Tesla', 'grapes'].includes(car)) {
   //code
}
Enter fullscreen mode Exit fullscreen mode

2. Shorthand for if with multiple And(&&) conditions

if(obj && obj.tele && obj.tele.stdcode) {
    console.log(obj.tele .stdcode)
}
Enter fullscreen mode Exit fullscreen mode

Use optional chaining (?.) to replace this snippet.

console.log(obj?.tele?.stdcode);
Enter fullscreen mode Exit fullscreen mode

3. Shorthand for checking null, undefined, and empty values of variable

if (name !== null || name !== undefined || name !== '') {
    let second = name;
}
Enter fullscreen mode Exit fullscreen mode

The simple way to do it is...

const second = name || '';
Enter fullscreen mode Exit fullscreen mode

4. Shorthand for switch case to select from multiple options

switch (number) {
  case 1:
     return 'Case one';
  case 2:
     return 'Case two';
  default:
     return;
}
Enter fullscreen mode Exit fullscreen mode

Use a map/ object

const data = {
  1: 'Case one',
  2: 'Case two'
};
//Access it using
data[num]
Enter fullscreen mode Exit fullscreen mode

5. Shorthand for functions for single line function

function example(value) {
  return 2 * value;
}
Enter fullscreen mode Exit fullscreen mode

Use the arrow function

const example = (value) => 2 * value
Enter fullscreen mode Exit fullscreen mode

6. Shorthand for conditionally calling functions

function height() {
    console.log('height');
}
function width() {
    console.log('width');
}
if(type === 'heigth') {
    height();
} else {
    width();
}
Enter fullscreen mode Exit fullscreen mode

Simple way

(type === 'heigth' ? height : width)()
Enter fullscreen mode Exit fullscreen mode

7. Shorthand for To set the default to a variable using if

if(amount === null) {
    amount = 0;
}
if(value === undefined) {
    value = 0;
}
console.log(amount); //0
console.log(value); //0
Enter fullscreen mode Exit fullscreen mode

Just Write

console.log(amount || 0); //0
console.log(value || 0); //0
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
rohit_pathak_8256cfd6c9ef profile image
Rohit Pathak

it's really nice and helpful. thanks for sharing.

Keep posting

Collapse
 
devsimc profile image
Simc Dev

Cheers,