Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

What is the ? in JavaScript

Understanding the Mysterious ? in JavaScript

JavaScript is full of delightful surprises, and one of those is the humble question mark, or ?. This little symbol packs a powerful punch and can make your life as a programmer much easier if you understand how to wield it properly. Let's delve into its mysteries.

The Conditional (Ternary) Operator

When you see a ? in JavaScript, it's mostly used as part of the conditional (ternary) operator. Now, let's break down this fancy term. It's called "conditional" because it allows us to choose between two outcomes based on a certain condition. It's called "ternary" because it's the only JavaScript operator that takes three operands (inputs).

How Does It Work?

Think of the ternary operator like a mini if...else statement. Here's what it looks like:

condition ? expressionIfTrue : expressionIfFalse

Imagine the ? as a tiny, code-loving robot. First, it checks if the condition on its left is true. If it is, it executes the code on the immediate right (the expressionIfTrue). If the condition is false, it skips over to the far right and runs the expressionIfFalse.

A Real-Life Example

Let's say we have a variable isRaining and we want to decide what to wear based on its value. In JavaScript, we can write:

let isRaining = true;
let outfit = isRaining ? 'Take an umbrella!' : 'Sunglasses are a good idea!';
console.log(outfit);

If you run this code, it will print 'Take an umbrella!' because isRaining is true.

The Optional Chaining Operator

Another appearance of ? in JavaScript is in optional chaining. Imagine you're trying to access a property deep within an object, but you're not sure if all the levels of the object exist. If you try to access a property that doesn't exist, JavaScript usually throws an error and stops your code.

That's where optional chaining comes in. By using ?., you're telling JavaScript: "Hey, if this property exists, give me its value. If it doesn't, just return undefined and move on."

How Does It Work?

Let's say we have an object person:

let person = {
  name: 'Jane',
  pet: {
    name: 'Fluffy',
    breed: 'Labrador'
  }
};

We can use optional chaining to access breed:

console.log(person.pet?.breed); // Outputs: Labrador

But if we try to access a property that doesn't exist, instead of throwing an error, JavaScript will return undefined:

console.log(person.pet?.color); // Outputs: undefined

The Nullish Coalescing Operator

The last use of ? we'll cover is in the nullish coalescing operator ??. This operator returns the first operand if it's not null or undefined. Otherwise, it returns the second operand.

How Does It Work?

let value = null ?? 'default value';
console.log(value); // Outputs: 'default value'

In this case, because the value on the left of ?? is null, the operator returns the value on the right.

Wrapping Up

The ? in JavaScript is like a Swiss Army knife, compact but versatile. It serves as a ternary operator, facilitating decision-making in your code. It also acts as a safety net in optional chaining, preventing errors when accessing non-existing properties. Lastly, it proves its worth in the nullish coalescing operator, providing a fallback value when dealing with null or undefined variables.

Mastering these tools will make you a more effective JavaScript programmer, able to write clean, efficient, and error-resistant code. So, next time you see a ? in your code, don't question its purpose. Instead, appreciate its versatility and the elegance it brings to your JavaScript journey.