Question Mark (?) Operators ASAP
Tags: javascript, programming, tutorial, functional
Published: 2022-01-24 00:58:22


&nbsp;&nbsp;&nbsp;&nbsp;If you've ever used conditionals in your code you've seen ``if`` statements, and if you've seen ``if`` statements you've seen them nested several layers deep. In your personal project this could be simply annoying and cause problems down the road but in production code this can be really problematic. 

&nbsp;&nbsp;&nbsp;&nbsp;The ternary operator, ``?:``, is one Question Mark operator and a feature in some programming languages that makes conditional statemnts cleanier and easier to read. The basic syntax goes like this:

```typescript
condition ? if true : else;
```
In use this would look like this:

```typescript
const foo = true ? 1 : 0;
```
In this snippet, ``foo`` is 1, since the condition is ``true``, and ``true`` is (obviously) a truthy value.

If you're not sure what truthy/falsy values are just think of it this way:

0, ``false``, ``undefined``, ``NaN``, empty strings, arrays, objects etc are falsy. All other values are truthy.

If an expressions result is a falsy value then the statement itself is falsy. 

```typescript
0 == 1
```
This is a falsy statement, because it returns ``false``.

In this article I'll teach you how to use Question Mark operators, and their uses in ES2020.


## Usages

<br>
 
### Ternary Operator (``?``)

The first implementation of the ``?`` in JavaScript is the simplest one, the one I showed at the beginning of the article, the ternary operator (``?:``).

```typescript
conditon ? true : false;
```
If the condition here is true, then the first value after the ``?`` is either assigned or called.

<br>

### Nullish Coalescing/Assignment (``??``)

The next implementation is the ``??`` or nullish operator, which is used in Nullish Coalescing.

Nullish coalescing looks something like this:

```typescript
const value = true ?? false;
```

&nbsp;&nbsp;&nbsp;&nbsp;``value`` will become ``true``. You may be wondering now what's the difference between this and the Logical Or operator (``||``)? The ``||`` operator worked well but a problem a lot of people run into sometimes is that it considered values like empty compound types (``{}``, ``[]``, ``""``) and 0 as falsy so the need for a logical operator that only considered ``null`` and ``undefined`` as falsy naturally arose.

<br>

### Logical Nullish Assignment (``??=``)

```typescript
x ??= y;
```


The third question mark operator is called the Logical Nullish assignment operator, ``??=``. The gist of this operator is to assign a value ``y`` to a value ``x`` if ``x`` is ``null`` or ``undefined``, and only if it is. 

```typescript
let val = null;
val ??= 10;

// val is now 10, because it was null before


let num = 0;
num ??= 20;

// num stays as 0, because 0 is neither undefined nor null

let egg;
egg ??= "scrambled";

// egg is now "scrambled" becuase uninitialized variables are undefined
```

<br>


### Optional Chaining (``?.``)

&nbsp;&nbsp;&nbsp;&nbsp;The last and latest question mark operator is a very useful feature. It allows us to access a value on the value of an object only if it exists. It gets rid of ``if`` statements and ``try..catch`` statements .In the event of a ``null`` or ``undefined`` value being returned, there is no error thrown, the value is just ``null`` or ``undefined``. 

```typescript
const John = {
    firstName: "John",
    lastName: "Doe",
    age: 21,
    parents: ["Jack", "Jane"]
}

console.log(John.lastName);

// => "John"

console.log(John.bestFriend?.age);

// => undefined

console.log(John.bestFriend.age);

// => Error: Cannot read properties of undefined
```
<br>

### Use in Other languages

&nbsp;&nbsp;&nbsp;&nbsp;Question mark operators exist in a large number of programming languages, as ternary operations are originally a mathematical concept, these are some examples:

| Language  | Ternary or similar expression |   
|---|---|
|  C++, Java, JavaScript, C#, C, Bash, Ruby, Swift, PHP | ``condition ? if true : else;``  |   
| Python  | ``value if conditon else false``   |   
| Rust  | ``if condition {true} else {false}``  |
| R| ``if (condition) true else false``  |   
| Go | No implimentation |
| Haskell | ``if condition then true else false`` |


### Conclusion

&nbsp;&nbsp;&nbsp;&nbsp;Now with your new-found knowledge of the question mark operators you can go impress your friends, colleagues, teammates or classmates, but don't overdo it. Question mark operators are prone to misuse and can make code unreadable if overused, so don't try to force it in whenever you can.


<br>

#### Sources
 
[MDN Docs: Conditional (ternary) operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator) <br>
[MDN Docs: Nullish coalescing operator (??)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator) <br>
[MDN Docs: Logical nullish assignment (??=)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_nullish_assignment) <br>
[MDN Docs: Optional chaining (?.)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining) <br>
[Wikipedia: ?:](https://en.wikipedia.org/wiki/%3F:)