If you are new to JavaScript, the question mark after a variable may be confusing to you. Letâs shed some light into it. The question mark in JavaScript is commonly used as conditional operator â called ternary operator when used with a colon (:) and a question mark (?) â to assign a variable name conditionally.
Either the expression is true and returns the value after the question mark (?) or the expression is false and returns the value after the colon (:).
This kind of JavaScript variable declaration is used as a shorthand though. You can achieve the same with the âif-elseâ-statement in JavaScript as conditional operator in contrast to the ternary operator, but it turns out more verbose:
If this is not what you are looking for, then maybe you are searching for JavaScriptâs optional chaining feature. It is used to assign a variable conditionally:
If the person has no pet, the output would be undefined without throwing a JavaScript exception.
When this feature was not available in JavaScript, it was common to use the AND (&&) operator or the ternary operator (?:) from before to avoid any JavaScript exceptions:
Most commonly you will find the question mark in JavaScript for these two use cases. Either it is used as shorthand conditional operator instead of the commonly used âif-elseâ-statement or as optional chaining operator to assign variables conditionally without hitting an exception.