9 Shorthands We Need to Know for Writing JavaScript

ยท

2 min read

1 if..else

const x = 100
if(x>100) {
  console.log('over 100!');
} else {
  console.log('OK');
}

console.log((x>100) ? 'over 100!' : 'OK');

// output
OK
let result = 0;
if(result ===0) {
  result = 10;
} else {
  result = 100;
}

let result =0;
result = result === 0 ? 10 : 100;

// output
result 10

2 if with multiple conditions

const x = 'hello'

if(x ==='123' || x === 'world' || x === 'ok' || x === 'hello' ) {
  console.log('hi ๐Ÿ‘‹');
}

const myConditions = ['123', 'world', 'ok', 'hello']
if(myConditions.includes(x)) {
  console.log('hi ๐Ÿ‘‹');
}

// output
hi ๐Ÿ‘‹

3 Variable

let a = 10;
let b = 10;

let a, b = 10;

// this won't work NG
let a = 10;
let b = 100;

let a, b = 10, 100;

// this is ok
let a = 10, b =100;

let [a, b] = [10, 100];

4 increment/decrement + ฮฑ

a = a + 1;
b = b - 1;
c = c * 10;
d = d / 10;

a++;
b--;
c *= 10;
d /= 10;

5 Spread operator

const x = [1,3,5];
const y = [2,4,6];
const result = y.concat(x);

const result_with_spread = [...y, ...x];

// output
[2, 4, 6, 1, 3, 5]

6 Template literals

This isn't really short but intuitive. Especially, if we need to put space in the text, Template literals is very useful.

x = 'hello'

console.log(x + ' world');

console.log(`${x} world`);

// output
hello world

Template literals with a new line

console.log("hello \n" + "world");

console.log(`hello
world`);

7 pow

const result = Math.pow(10, 3);

const result = 10**3

// output
1000

8 Object property

The property name and variable name must be the same.

name='koji'
sex='male'

const myObj = {name: name, sex: sex}

const anotherMyObj = {name, sex}

// output
console.log(myObj)
{name: "koji", sex: "male"}
console.log(anotherMyObj)
{name: "koji", sex: "male"}
const kojiObj = {name: "koji", sex: "male"};

const {name, sex} = kojiObj;

// output
console.log(name, sex);
koji,male

9 Repeat

const repeatNum = 10;

let resultString = '';
for(let i = 0; i < repeatNum; i ++) {
   resultString += 'hi ';
}
console.log(resultString);

'hi '.repeat(repeatNum);

// output
hi hi hi hi hi hi hi hi hi hi "

cover iamge Photo by Shahadat Rahman on Unsplash