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 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to uninstall Cocoapods from the Mac OS?

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
PHP arrays for US states’ full names and abbreviationsPHPHow to add before after image effect using pure CSS?CSSModules and its Core features in JavaScriptJavaScriptHow to add a select dropdown in React?ReactIs monitoring an employee’s work on a computer a desirable or undesirable activity?MiscellaneousHow to create a Bootstrap style accordion using CSS and JavaScript?CSS