Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Concept Entry] Javascript: Nullish Coalescing #5881

Merged
merged 6 commits into from
Jan 8, 2025
Merged
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
---
Title: 'Nullish Coalescing'
Description: 'Returns the right-hand operand if the left-hand operand is null or undefined, otherwise, it returns the left-hand operand.'
Subjects:
- 'Web Development'
- 'Computer Science'
Tags:
- 'Comparison'
- 'Logical'
- 'Operators'
CatalogContent:
- 'introduction-to-javascript'
- 'paths/front-end-engineer-career-path'
---

A JavaScript **nullish coalescing** (`??`) operator is a logical operator that evaluates the left-hand operand and returns it if it is not nullish (i.e., not `null` or `undefined`). Otherwise, it returns the right-hand operand.

## Syntax

```pseudo
value1 ?? value2
```

- `value1`: The first operand to check if it is nullish (`null` or `undefined`).
- `value2`: The second operand that acts as the default value, returned only if `value1` is nullish.

## Example

The following example demonstrates the use of the nullish coalescing operator to provide a default value when the variable is `null` or `undefined`:

```js
const age = undefined;
const defaultAge = 18;

console.log(age ?? defaultAge);
```

The above code produces the following output:

```shell
18
```

## Codebyte Example

The following example uses the nullish coalescing operator (`??`) to return "Guest" as a fallback value when `name` is `null`:

```codebyte/javascript
const name = null;
const defaultName = "Guest";

console.log(name ?? defaultName);
```
Loading