Question Mark (?) Operators ASAP

ayubf

ayubf

Posted on January 24, 2022

Question Mark (?) Operators ASAP

    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.

    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:

condition ? if true : else;
Enter fullscreen mode Exit fullscreen mode

In use this would look like this:

const foo = true ? 1 : 0;
Enter fullscreen mode Exit fullscreen mode

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.

0 == 1
Enter fullscreen mode Exit fullscreen mode

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

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 (?:).

conditon ? true : false;
Enter fullscreen mode Exit fullscreen mode

If the condition here is true, then the first value after the ? is either assigned or called.

Nullish Coalescing/Assignment (??)

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

Nullish coalescing looks something like this:

const value = true ?? false;
Enter fullscreen mode Exit fullscreen mode

    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.

Logical Nullish Assignment (??=)

x ??= y;
Enter fullscreen mode Exit fullscreen mode

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.

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
Enter fullscreen mode Exit fullscreen mode

Optional Chaining (?.)

    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.

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
Enter fullscreen mode Exit fullscreen mode

Use in Other languages

    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

    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.

Sources

MDN Docs: Conditional (ternary) operator

MDN Docs: Nullish coalescing operator (??)

MDN Docs: Logical nullish assignment (??=)

MDN Docs: Optional chaining (?.)

Wikipedia: ?:

💖 💪 🙅 🚩
ayubf
ayubf

Posted on January 24, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Javascript: Functional Composition
javascript Javascript: Functional Composition

September 5, 2022

Question Mark (?) Operators ASAP
javascript Question Mark (?) Operators ASAP

January 24, 2022

Decomposing Composition
javascript Decomposing Composition

December 16, 2021