Popular shorthand techniques in JavaScript

Print Friendly, PDF & Email

The shorthand techniques can help you to write optimized code and let you achieve your goal with less coding. Let’s discuss some of the shorthand tips and tricks of JavaScript one by one.

Declaring variables

// longhand
var x;
var y;
var z = 5;

// shorthand
var x, y, z = 5;

Ternary operators

// longhand
let isEven;
if (number%2 === 1) {
  isEven = false;
} else {
  isEven = true;
}

// shorthand
let isEven = number%2 === 0 ? true : false;
// shorthand - another version
let isEven = number%2 === 0

Assignment operators

// longhand
x = x + y;
x = x - y;

// shorthand
x += y;
x -= y;

Boolean comparison

let isEven = false;
let number;

// longhand
if (number % 2 === 0) {
  isEven = true;
} else {
  isEven = false;
}

// shorthand

isEven = number % 2 === 0;

Arrow functions

// longhand

function isEven(number) {
  if (number % 2 === 0) {
    return true;
  } else {
    return false;
  }
}

// shorthand
const isEven = number => {
   return number % 2 === 0;
}Ả

Operators on Array, Object, etc.

// longhand
"Tom Nguyen".chartAt(0); // output: 'T'

// shorthand
"Tom Nguyen"[0]; // output: 'T'

// longhand
let members = Array();
members[0] = "Tom";
members[1] = "Lily";
members[2] = "Tony";
members[3] = "Ethan";

// shorthand
let a = ["Tom", "Lily", "Tony", "Ethan"];

 

 

Voilà!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.