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) {
}
```
```

Shorthand

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

if(!~arr.indexOf(item)) {