Published

Javascript Shorthand Techniques

Authors
  • avatar
    Name
    xNoJustice

Declaring Variables

Longhand
let x
let y
let z = 'a'
Shorthand
let x,
  y,
  z = 'a'

Declaring Variables 2

Longhand
let a = 100
let b = 200
let c = 300
Shorthand
let a, b, c = 100, 200, 300;

Ternary Operators

Longhand
let number
if (x > 9) {
  number = true
} else {
  number = false
}
Shorthand
let number = x > 9

Ternary Operators 2

Longhand
let marks = 26
let grade
if (marks >= 90) {
  grade = 'A'
} else if (marks >= 80) {
  grade = 'B'
} else if (marks >= 70) {
  grade = 'C'
} else {
  grade = 'D'
}
Shorthand
let grade = marks >= 90 ? 'A' : marks >= 80 ? 'B' : marks >= 70 ? 'C' : 'D'

Assignment Operators

Longhand
x = x + y
x = x - y
Shorthand
x += y
x -= y

Spread Operators

Longhand
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const arr3 = [];

for (let i = 0; i < arr1.length; i++) {
  arr3.push(arr1[i]);
}
for (let i = 0; i < arr2.length; i++) {
  arr3.push(arr2[i]);
}
Shorthand
const arr3 = [...arr1, ...arr2];

Destructuring Assignment

Longhand
let user = {
  name: "John Doe",
  age: 30,
  address: "123 Main Street",
};
let name = user.name;
let age = user.age;
let address = user.address;
Shorthand
const { name, age, address } = user;

Destructuring Assignment 2

Longhand
const arr = [100, 200, 300];
let a = arr[0];
let b = arr[1];
let c = arr[2];
Shorthand
const [a, b, c] = arr;

Switch Case

Longhand
switch (something) {
  case 1:
    doSomething()
    break
  case 2:
    doSomethingElse()
    break
}
Shorthand
const cases = {
  1: doSomething,
  2: doSomethingElse,
}

If Presence

Longhand
if (boolGoesHere === true) {
}
Shorthand
if (boolGoesHere) {
}

Arrow Functions

Longhand
function sayHello(name) {
  console.log('Hello', name)
}
Shorthand
sayHello = (name) => console.log('Hello', name)

charAt()

Longhand
'myString'.charAt(0)
Shorthand
'myString'[O]