Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
January 24, 2022 12:58 am GMT

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;

In use this would look like this:

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.

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

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;

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;

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;

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 beforelet num = 0;num ??= 20;// num stays as 0, because 0 is neither undefined nor nulllet egg;egg ??= "scrambled";// egg is now "scrambled" becuase uninitialized variables are undefined

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);// => undefinedconsole.log(John.bestFriend.age);// => Error: Cannot read properties of undefined

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:

LanguageTernary or similar expression
C++, Java, JavaScript, C#, C, Bash, Ruby, Swift, PHPcondition ? if true : else;
Pythonvalue if conditon else false
Rustif condition {true} else {false}
Rif (condition) true else false
GoNo implimentation
Haskellif 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: ?:


Original Link: https://dev.to/ayubf/question-mark-operators-asap-316d

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To