Skip to content

Question mark after variable JavaScript | Example code

  • by

The question mark after the variable is called Optional chaining (?.) in JavaScript. The optional chaining operator provides a way to simplify accessing values through connected objects when it’s possible that a reference or function may be undefined or null.

The question mark in JavaScript is commonly used as a conditional operator — called ternary operator when used with a colon (:) and a question mark (?) — to assign a variable name conditionally.

A question mark after variable JavaScript

Simple example code if you are trying to access the properties of a non-declared “obj” object, you will get an error:

<!DOCTYPE html>
<html>
<body>

  <script>
   console.log(obj?.someProperty);  

 </script>

</body>
</html> 

Output:

question mark after variable JavaScript

But if you have already declared your object and trying to access the property which is Null or undefined, you will get an undefined result :

const obj = {}
console.log(obj?.someProperty);

Output: undefined

Source: stackoverflow.com/

Do comment if you have any doubts or suggestions on this JS question topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading