DEV Community

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

Simc Dev on August 04, 2022

1. Shorthand for if with multiple OR(||) conditions if (car === 'audi' || car === 'BMW' || car === 'Tesla') { //code } ...
Collapse
 
dred profile image
Anton B •

On 6th example i would rather use it in that way
type === 'heigth' ? height() : width()

it is more clear for me and for other i guess, and can be passed different arguments to functions

Collapse
 
mikejacobson profile image
Mike Jacobson •

I agree. It also makes it easier to do a global search for all places where those functions are invoked.

Collapse
 
fen1499 profile image
Fen •

7th example can be written with ??. The difference is that values that evaluate to false would pass but if you use || they don't

Example:

false ?? 0 // false
false || 0 // 0
Enter fullscreen mode Exit fullscreen mode
Collapse
 
mikcat profile image
mikcat •

Be careful if you refactor switch by object, because switch uses strict uses strict comparison ===.

console.log(data['1']); will return 'Case one' but switch('1') will jump to the default branch.

Collapse
 
balastrong profile image
Leonardo Montini •

The 7th example is not entirely correct though.

You replace

if(amount === null) {
    amount = 0;
}
Enter fullscreen mode Exit fullscreen mode

with

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

But if amount is undefined, it will not enter your if, but still undefined || 0 returns 0.

In short, you can't replace === null with the || operator as the behaviour is slightly different.

Collapse
 
jacksonkasi profile image
Jackson Kasi •

thank for share with us :)

Collapse
 
devsimc profile image
Simc Dev •

Cheers

Collapse
 
dmk1111 profile image
dmk1111 •
  1. in suggested option console.log will still fire with undefined but with if case it won't fire;
  2. works in this particular case. In case you have to return default value it won't work
Collapse
 
dannyengelman profile image
Danny Engelman •

'Audi,BMW,Tesla,Daf,Volkswagen'.includes(car);

or even without ,

Collapse
 
chatbim profile image
mustapha chatbi •

this would be a good trick if used just on typescript where car has to have enum type that allows only mentioned car brands
and here is why ( counter example on js )
Image description

Collapse
 
orliesaurus profile image
orliesaurus •

good reminders always easy to forget optional chaining!

Collapse
 
ricky11 profile image
Rishi U •

2nd Example optional chaining will return undefined if console.log like that, you would probably need to do use a ternary instead if you didn't want to print undefined.
but thanks for this.

Collapse
 
mjcoder profile image
Mohammad Javed •

Good examples - thank you. 🙌

Collapse
 
citronbrick profile image
CitronBrick •

Did not know about number 6 before. It's really cool !

Collapse
 
devsimc profile image
Simc Dev •

Cheers