YogeshChauhan . com

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
}

amazon

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 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

Jun 16 What are Stored Procedures for SQL Server? Jun 16 What are Class Constants in PHP? Jun 15 A short basic guide on states in React Jun 15 How to define constants in PHP? Jun 15 How to define visibility for a property in PHP? Jun 15 How to use @if and @else in SCSS?

You might also like these

include, include_once, require, require_once in PHPPHPHow to create a sidebar using pure CSS?CSSFETCH clause in PostgreSQLPostgresHow to remove N/A from Radio Button list in Drupal?DrupalHow to add new elements with swing animation using JavaScript and CSS?CSSALTER DATABASE in PostgreSQLPostgres