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
}


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

Recently Posted

#Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS? #Aug 1 What is Zdog? #Aug 1 How to add before after image effect using pure CSS? #Jul 31 Add animation to your skills bar using CSS #Jul 31 Use SwiperJS to create mobile touch sliders fast
You might also like these
12 URLSearchParams methods in JavaScriptJavaScriptCheck If a String Contains a Specific Word in PHPPHPCSS align-items property examplesCSSHow to read Standard Input in Swift?SwiftHow to change the Login Logo in WordPress?WordPressHow to make HTML form interactive and using CSS?CSS