Skip to content

Question mark in JavaScript | Operator

  • by

The conditional or question mark operator is represented by a “?” question mark in JavaScript. This operator is used in conditional statements, and when paired with a :, can function as a compact alternative to if...else statements.

Main Uses for the Question Mark

  1. Ternary Operator
  2. Optional Chaining
  3. Nullish Coalescing

The general syntax of the conditional operator is as follows:

condition ? expressionIfTrue : expressionIfFalse;

Here’s how it works:

  1. The condition is evaluated.
  2. If the condition is true, the expressionIfTrue is executed.
  3. If the condition is false, the expressionIfFalse is executed.

Here’s an example that demonstrates the usage of the conditional (ternary) operator:

var age = 20;
var message = (age >= 18) ? "You are an adult" : "You are a minor";

console.log(message); // Output: "You are an adult"

The question mark in JavaScript

Simple example code.

Ternary Operator

It takes three operands: a condition followed by a question mark (?), then an expression to execute if the condition is truthy followed by a colon (:), and finally, the expression to execute if the condition is falsy.

Read more: Ternary Operator

<!DOCTYPE html>
<html>
<body>

  <script>
   var age = 26;
   var beverage = (age >= 21) ? "Beer" : "Juice";
   console.log(beverage);
 </script>

</body>
</html> 

Output:

Question mark in JavaScript Operator

Optional Chaining

This operator enables you to read the value of a property located deep within a chain of connected objects without having to check that each reference in the chain is valid.

const adventurer = {
  name: 'Alice',
  cat: {
    name: 'Dinah'
  }
};

const dogName = adventurer.dog?.name;
console.log(dogName);

Output: undefined

Nullish Coalescing

This is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.

const foo = null ?? 'default string';
console.log(foo);
// expected output: "default string"

const baz = 0 ?? 42;
console.log(baz);
// expected output: 0

source: developer.mozilla.org

Do comment if you have any doubts or suggestions on this JS Operator 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

Your email address will not be published. Required fields are marked *