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
}
⚽ Live Match: devsimc/change your old methods for writing a javascript code shorthands for javascript code hp - Jadwal Siaran Langsung ⚽ Live Match: devsimc/change your old methods for writing a javascript code shorthands for javascript code hp - Jadwal Siaran Langsung

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
}
⚽ Live Match: devsimc/change your old methods for writing a javascript code shorthands for javascript code hp - Jadwal Siaran Langsung ⚽ Live Match: devsimc/change your old methods for writing a javascript code shorthands for javascript code hp - Jadwal Siaran Langsung

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

if(obj && obj.tele && obj.tele.stdcode) {
    console.log(obj.tele .stdcode)
}
⚽ Live Match: devsimc/change your old methods for writing a javascript code shorthands for javascript code hp - Jadwal Siaran Langsung ⚽ Live Match: devsimc/change your old methods for writing a javascript code shorthands for javascript code hp - Jadwal Siaran Langsung

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

console.log(obj?.tele?.stdcode);
⚽ Live Match: devsimc/change your old methods for writing a javascript code shorthands for javascript code hp - Jadwal Siaran Langsung ⚽ Live Match: devsimc/change your old methods for writing a javascript code shorthands for javascript code hp - Jadwal Siaran Langsung

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

if (name !== null || name !== undefined || name !== '') {
    let second = name;
}
⚽ Live Match: devsimc/change your old methods for writing a javascript code shorthands for javascript code hp - Jadwal Siaran Langsung ⚽ Live Match: devsimc/change your old methods for writing a javascript code shorthands for javascript code hp - Jadwal Siaran Langsung

The simple way to do it is...

const second = name || '';
⚽ Live Match: devsimc/change your old methods for writing a javascript code shorthands for javascript code hp - Jadwal Siaran Langsung ⚽ Live Match: devsimc/change your old methods for writing a javascript code shorthands for javascript code hp - Jadwal Siaran Langsung

4. Shorthand for switch case to select from multiple options

switch (number) {
  case 1:
     return 'Case one';
  case 2:
     return 'Case two';
  default:
     return;
}
⚽ Live Match: devsimc/change your old methods for writing a javascript code shorthands for javascript code hp - Jadwal Siaran Langsung ⚽ Live Match: devsimc/change your old methods for writing a javascript code shorthands for javascript code hp - Jadwal Siaran Langsung

Use a map/ object

const data = {
  1: 'Case one',
  2: 'Case two'
};
//Access it using
data[num]
⚽ Live Match: devsimc/change your old methods for writing a javascript code shorthands for javascript code hp - Jadwal Siaran Langsung ⚽ Live Match: devsimc/change your old methods for writing a javascript code shorthands for javascript code hp - Jadwal Siaran Langsung

5. Shorthand for functions for single line function

function example(value) {
  return 2 * value;
}
⚽ Live Match: devsimc/change your old methods for writing a javascript code shorthands for javascript code hp - Jadwal Siaran Langsung ⚽ Live Match: devsimc/change your old methods for writing a javascript code shorthands for javascript code hp - Jadwal Siaran Langsung

Use the arrow function

const example = (value) => 2 * value
⚽ Live Match: devsimc/change your old methods for writing a javascript code shorthands for javascript code hp - Jadwal Siaran Langsung ⚽ Live Match: devsimc/change your old methods for writing a javascript code shorthands for javascript code hp - Jadwal Siaran Langsung

6. Shorthand for conditionally calling functions

function height() {
    console.log('height');
}
function width() {
    console.log('width');
}
if(type === 'heigth') {
    height();
} else {
    width();
}
⚽ Live Match: devsimc/change your old methods for writing a javascript code shorthands for javascript code hp - Jadwal Siaran Langsung ⚽ Live Match: devsimc/change your old methods for writing a javascript code shorthands for javascript code hp - Jadwal Siaran Langsung

Simple way

(type === 'heigth' ? height : width)()
⚽ Live Match: devsimc/change your old methods for writing a javascript code shorthands for javascript code hp - Jadwal Siaran Langsung ⚽ Live Match: devsimc/change your old methods for writing a javascript code shorthands for javascript code hp - Jadwal Siaran Langsung

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
⚽ Live Match: devsimc/change your old methods for writing a javascript code shorthands for javascript code hp - Jadwal Siaran Langsung ⚽ Live Match: devsimc/change your old methods for writing a javascript code shorthands for javascript code hp - Jadwal Siaran Langsung

Just Write

console.log(amount || 0); //0
console.log(value || 0); //0
⚽ Live Match: devsimc/change your old methods for writing a javascript code shorthands for javascript code hp - Jadwal Siaran Langsung ⚽ Live Match: devsimc/change your old methods for writing a javascript code shorthands for javascript code hp - Jadwal Siaran Langsung

Top comments (22)

⚽ Live Match: devsimc/change your old methods for writing a javascript code shorthands for javascript code hp - Jadwal Siaran Langsung
 
mayallo profile image
Mohamed Mayallo • • Edited

8. Shorthand to remove duplicates from array

Array.from(new Set([1, 2, 3, 1, 2]))
⚽ Live Match: devsimc/change your old methods for writing a javascript code shorthands for javascript code hp - Jadwal Siaran Langsung ⚽ Live Match: devsimc/change your old methods for writing a javascript code shorthands for javascript code hp - Jadwal Siaran Langsung

9. Shorthand to conditionally insert a key/value in an object

let isTrue = false;
let obj = {
    name: 'hello',
    ...(isTrue && { age: 30 })
}
console.log(obj)
⚽ Live Match: devsimc/change your old methods for writing a javascript code shorthands for javascript code hp - Jadwal Siaran Langsung ⚽ Live Match: devsimc/change your old methods for writing a javascript code shorthands for javascript code hp - Jadwal Siaran Langsung
⚽ Live Match: devsimc/change your old methods for writing a javascript code shorthands for javascript code hp - Jadwal Siaran Langsung
 
h_sifat profile image
Muhammad Sifat Hossain •

Thanks for the number 9. I already knew 1 to 8 but I never thought of using number 9 method.

⚽ Live Match: devsimc/change your old methods for writing a javascript code shorthands for javascript code hp - Jadwal Siaran Langsung
 
jonrandy profile image
Jon Randy 🎖️ • • Edited

The two examples on number (3) are not equivalent. In more ways than one.

Other examples are also suffering similarly. Within each example, the code snippets should ideally be functionally equivalent in order to make a fair comparison.

⚽ Live Match: devsimc/change your old methods for writing a javascript code shorthands for javascript code hp - Jadwal Siaran Langsung
 
corscheid profile image
Corey Scheideman •

If an arrow function looks too long on one line, just use parens or curly brackets.

// returns undefined
const logSomething = () => {
  console.log('Something')
}

// returns string
const getValue = (isX) => (
  isX ? 'x' : 'not x'
)
⚽ Live Match: devsimc/change your old methods for writing a javascript code shorthands for javascript code hp - Jadwal Siaran Langsung ⚽ Live Match: devsimc/change your old methods for writing a javascript code shorthands for javascript code hp - Jadwal Siaran Langsung
⚽ Live Match: devsimc/change your old methods for writing a javascript code shorthands for javascript code hp - Jadwal Siaran Langsung
 
leob profile image
leob •

What is it with this if(amount === null) { syntax where people are omitting the space between the if and the (? I'm getting the impression that it's a trend, I see it more and more. Is it because "if()" is being seen as a function, or something?

 
corscheid profile image
Corey Scheideman • • Edited

What do you mean "more common"? I see the form of what I've put here in my previous comment very very often. And in my opinion, pound for pound, it's really not much less readable than

// returns undefined
function logSomething() {
  console.log('Something')
}

// returns string
function getValue (isX) {
  return  isX ? 'x' : 'not x'
}
⚽ Live Match: devsimc/change your old methods for writing a javascript code shorthands for javascript code hp - Jadwal Siaran Langsung ⚽ Live Match: devsimc/change your old methods for writing a javascript code shorthands for javascript code hp - Jadwal Siaran Langsung

Although I'll admit, that I personally never use

function foo() { /* ... */ }
⚽ Live Match: devsimc/change your old methods for writing a javascript code shorthands for javascript code hp - Jadwal Siaran Langsung ⚽ Live Match: devsimc/change your old methods for writing a javascript code shorthands for javascript code hp - Jadwal Siaran Langsung

or

function() { /*...*/ }
⚽ Live Match: devsimc/change your old methods for writing a javascript code shorthands for javascript code hp - Jadwal Siaran Langsung ⚽ Live Match: devsimc/change your old methods for writing a javascript code shorthands for javascript code hp - Jadwal Siaran Langsung

inline inside of outer statements, but rather more often as standalone functions.

 
corscheid profile image
Corey Scheideman • • Edited

Oh I see, fair point. I was thinking of JS in particular.

From my experience in Python,

foo = lambda x: print(x)
⚽ Live Match: devsimc/change your old methods for writing a javascript code shorthands for javascript code hp - Jadwal Siaran Langsung ⚽ Live Match: devsimc/change your old methods for writing a javascript code shorthands for javascript code hp - Jadwal Siaran Langsung

is indeed exceedingly rare compared to

def foo(x):
    print(x)
⚽ Live Match: devsimc/change your old methods for writing a javascript code shorthands for javascript code hp - Jadwal Siaran Langsung ⚽ Live Match: devsimc/change your old methods for writing a javascript code shorthands for javascript code hp - Jadwal Siaran Langsung

I guess because the former is probably just not "Pythonic". Inline lambda functions in python are imo ugly and much less readable because of their syntax and just not as typical as inline arrows are in JS, for good reason. I think these Python lambdas are only really supposed to be for quick and cheap one-liners where the function only runs a single statement and/or returns the value of it.

 
corscheid profile image
Corey Scheideman • • Edited

All good. Makes sense :)

Hah! Yeah, I saw the term "Pythonic" thrown around in the Python community for a while. I particularly remember seeing it a fair bit on Stack Overflow in response to whenever someone posted something super hacky that would be fine in whatever language but there's a more natural and readable solution built into Python for better simple elegance or something like that.

⚽ Live Match: devsimc/change your old methods for writing a javascript code shorthands for javascript code hp - Jadwal Siaran Langsung
 
h_sifat profile image
Muhammad Sifat Hossain •

Nice tips. But I've a question about the number 1 (though I use it sometimes in my code). Seems like for every check it'll create a new array. Is that inefficient?

⚽ Live Match: devsimc/change your old methods for writing a javascript code shorthands for javascript code hp - Jadwal Siaran Langsung
 
kodikos profile image
Jodi Winters •

Yes, but not likely for that reason. I did a quick crude benchmark and Firefox runs the includes-style check at almost 10x slower. Chrome runs them even slower, which is a point that implementations vary. You don't want to run code like that in a tight loop! I ran an extra check with the array creation outside the loop, it didn't improve speed by much. So it's not so much the creation of the new array, I suspect that can be optimised by runtime code compilers - it'll be the looping and checking in the includes method that takes time. I also use it in code, but I'll have to be mindful of where I use it. Alas, many shorthands are actually quite poor for optimisations.

⚽ Live Match: devsimc/change your old methods for writing a javascript code shorthands for javascript code hp - Jadwal Siaran Langsung
 
h_sifat profile image
Muhammad Sifat Hossain •

Thanks for the benchmark result. I'll also try to be mindful about it.

⚽ Live Match: devsimc/change your old methods for writing a javascript code shorthands for javascript code hp - Jadwal Siaran Langsung
 
adam_cyclones profile image
Adam Crockett 🌀 •

4 would crash on a default case?

⚽ Live Match: devsimc/change your old methods for writing a javascript code shorthands for javascript code hp - Jadwal Siaran Langsung
 
kodikos profile image
Jodi Winters •

No, it should return null. It would only crash if data didn't exist or wasn't an object. But in this case it's under your control so very unlikely. I don't know if strictmode modifies that behaviour, though. If you wanted default to return another value, when accessing it you would borrow from no. 3, i.e. data[num] || 'defaultValue'

⚽ Live Match: devsimc/change your old methods for writing a javascript code shorthands for javascript code hp - Jadwal Siaran Langsung
 
adam_cyclones profile image
Adam Crockett 🌀 •

Then I argue that, switch is for finite cases where all answers are known and default with no value being provided is an antipattern of switch which an object has no equivalent

⚽ Live Match: devsimc/change your old methods for writing a javascript code shorthands for javascript code hp - Jadwal Siaran Langsung Thread
 
kodikos profile image
Jodi Winters •

It might if it's a Map, but the code would be so fugly you might as well use a switch :D

⚽ Live Match: devsimc/change your old methods for writing a javascript code shorthands for javascript code hp - Jadwal Siaran Langsung
 
codingjlu profile image
codingjlu •

I've been JavaScripting for a long time, but some things you said were invaluable. I love the conditional function one; I can't believe I've never thought of that before! The multiple condition one is also brilliant. Thank you!