Yogesh Chauhan's Blog

If statement shorthand examples in JavaScript

in JavaScript on February 15, 2021

1. The Conditional Operator

I have another post on the Conditional Operator (aka Ternary Operator).

Longhand


const x = 0;

if (x >= 0) {
    y = "Positive";
} else {
    y =  "Negative";
}
console.log(y);
// "Positive"

Shorthand


var x = 0;
var y = (x >= 0) ? "Positive" : "Negative";
console.log(y);
// "Positive"

2. Short-circuit Evaluation

Short-circuiting is when an expression is stopped being evaluated as soon as its outcome is determined.

Longhand


if (a == b || c == d || e == f) {
     a == b;
}

Shorthand


a = 'foo';
b = a  || 'bar';
console.log(b); // prints foo

3. Without assignment operators

Longhand


if (a === true)
OR
if (a !== true)

Shorthand


if (a)
OR
if (!a)

The shorthand check will pass as long as a is a truthy value.

4. Default Parameter

Longhand


function f1(a, b, c) {
  if (a === undefined)
    a = 1;
  if (b === undefined)
    b = 2;
  return a + b + c;
}

Shorthand


sum = (a, b = 2, c = 3 ) => (a + b + c);
sum(1) 
//output: 6

5. Bitwise IndexOf

indexOf() function retrieves the position of the item you are looking for. If the item is not found, the value -1 is returned.

In JavaScript, 0 is considered falsy and numbers greater or lesser than 0 are considered truthy.

Longhand


if(array.indexOf(item) > -1) { 
  // item is found
}

if(array.indexOf(item) === -1) { 
  // item not found
}

Shorthand


if(~arr.indexOf(item)) {
  // item is found
}

if(!~arr.indexOf(item)) {
  // item not found
}


Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
How to Check If a Variable is an Integer, a Float, a Number, NaN, an Infinite or a Numeric in PHP?PHPCheck if any column has NULL values in PostgresPostgresHow to avoid element shift on border change while hovering in CSS?CSSDefault Values in SCSS (Sass)SCSSWhat are Null Sessions?MiscellaneousHow to add navigation menu in Angular 9 app?Angular