YogeshChauhan.com
If statement shorthand examples in JavaScript
February 15, 2021


1. The Conditional Operator

In this post, I explained 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
}

dreamhost

Leave a Reply

Most Read

#1 How to set opacity or transparency using CSS? #2 Pagination in CSS with multiple examples #3 How to check if radio button is checked or not using JavaScript? #4 How to make HTML form interactive and using CSS? #5 How to uninstall Cocoapods from the Mac OS? #6 How to add Read More Read Less Button using JavaScript?



Recently Posted

Feb 24 How to modify the latest post array using get_posts() in WordPress? Feb 22 WordPress: How to get ACF field values from another post? Feb 22 WordPress: How to print ACF repeater field values? Feb 22 WordPress: How to print ACF array field values? Feb 21 WordPress: How to get field values in Advanced Custom Fields? Feb 21 WordPress: How to add a Search Icon in Menus with toggle effect using jQuery?



You might also like these

How to check if radio button is checked or not using JavaScript?JavaScriptIntroduction to components and templates Part 1: Component MetadataAngularObservation of Human Behavior [Shopping Observation Example]MiscHow to Check If a Variable is an Integer, a Float, a Number, NaN, an Infinite or a Numeric in PHP?PHPThe 8 Golden Rules of Programming I Have Learned in My CareerMiscKilling A Project Part 3: How can an organization ensure that a doomed project is killed as early as possible?Misc