Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

What is question mark in JavaScript

The Mystery of the Question Mark in JavaScript

If you're new to JavaScript, you might have come across code snippets that feature a peculiar character - the question mark (?). This symbol may seem strange and even daunting to beginners, but fear not, this article aims to demystify the question mark and simplify its use in JavaScript.

The Conditional (Ternary) Operator

The first and perhaps the most common use of the question mark in JavaScript is as a conditional operator, otherwise known as the ternary operator. The word "ternary" comes from Latin and it means "composed of three parts". These three parts in JavaScript are a condition, a result for true, and a result for false, and they come together to form a short-hand for an if-else statement.

Here's the format:

(condition) ? expressionIfTrue : expressionIfFalse

Think of it as a mini if-else statement. If the condition is true, the code after the question mark (?), but before the colon (:), will run. If the condition is false, the code after the colon (:) will run.

For example, let's say you have a variable weather and you want to log different messages depending on whether it's 'sunny' or not:

let weather = 'sunny';

(weather === 'sunny') ? console.log('Wear sunglasses!') : console.log('Take an umbrella!');

In this example, because the weather variable is 'sunny', the message 'Wear sunglasses!' will be logged to the console.

The Optional Chaining Operator

The question mark also appears in another popular JavaScript feature - the optional chaining operator (?.). This operator allows 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.

Think of it as trying to find a specific book on a bookshelf. You know the book is in a specific section (object), on a specific shelf (sub-object), and it's the third book from the left (property). With optional chaining, if the section or the shelf doesn't exist, instead of getting an error, you'll get undefined.

Here's how it looks in JavaScript:

let user = {
  name: 'John',
  address: {
    street: '123 Main St',
    city: 'Anytown'
  }
};

console.log(user?.address?.city); // Anytown

In this example, if user is defined, ?. checks address, and if address is defined, it accesses city. If any of these objects were undefined, it would return undefined.

The Nullish Coalescing Operator

Lastly, the question mark is used in the nullish coalescing operator (??). This operator returns the first argument if it's not null or undefined. Otherwise, it returns the second argument.

Imagine you're deciding what to have for dinner. You check the fridge to see if there's any leftover pizza (first argument). If there's no pizza (null or undefined), you decide to order sushi instead (second argument).

Here's how it's used:

let leftoverPizza = null;
let dinner = leftoverPizza ?? 'sushi';

console.log(dinner); // sushi

In this example, because leftoverPizza is null, the nullish coalescing operator returns 'sushi' for dinner.

Wrapping Up

The question mark may seem like a mystery at first, but once you understand how it operates in different scenarios, it can be a powerful tool in your JavaScript arsenal. It's like a Swiss Army knife, providing different functionalities depending on the context.

Remember, the question mark can be a conditional (ternary) operator, an optional chaining operator, or a nullish coalescing operator. Each use case provides a valuable shortcut for writing cleaner, more efficient code.

As you continue your journey in learning JavaScript, don't be afraid of the question mark. Embrace it, play with it, and soon enough, you will be able to wield its power effortlessly. Happy coding!