Filling In a Request With ??=, ||= and &&=

Nadia needs the booking requests ready for the confirmation script. Fill Ana Silva’s blank hours box with the usual two hours, trim the choir’s padded note, and provide a replacement for a blank phone. Picking a value is only part of the job. You also need to store it in the request.

JavaScript’s logical assignment operators combine that choice with an assignment. You’ll use one line per field while keeping the hours and phone numbers the hirer supplied. Start with Ana’s hours, where a missing number needs a default.

Fill in Missing Hours

In Python, you check for None before changing Ana’s request. These snippets keep only the fields needed for each task:

Language: Python
DEFAULT_HOURS = 2
r = {"id": 105, "hours": None}

if r.get("hours") is None:
    r["hours"] = DEFAULT_HOURS

print(r["id"], r["hours"])

Python prints 105 2. Using .setdefault() here would keep the existing None.

In JavaScript, ??= means “assign only if the current value is null or undefined.” This loop applies it to the hours from all five requests:

Language: JavaScript
const DEFAULT_HOURS = 2;
const requests = [
  { id: 101, hours: 2 },
  { id: 102, hours: 3 },
  { id: 103, hours: 8 },
  { id: 104, hours: 1.5 },
  { id: 105, hours: null },
];

for (const r of requests) {
  r.hours ??= DEFAULT_HOURS;
  console.log(r.id, r.hours);
}

Only Ana’s hours change:

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.