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

Nadia’s script tidies each request in place before using it: two hours for Ana Silva’s blank hours box, a phone number for the choir, and a trimmed note. Python spells each fix as an if or an x = x or ... line and has no shorter form. JavaScript gives ??, ||, and && an assignment form that chooses by the same rule and stores the result, so each fix becomes one line.

Fill in the Gaps in Place

Each operator means “assign only if” the property passes its test. Here are Nadia’s three Python lines next to their JavaScript ports:

Python JavaScript Assigns when the value is
if r.get("hours") is None: r["hours"] = DEFAULT_HOURS r.hours ??= DEFAULT_HOURS null or undefined
r["phone"] = r["phone"] or ... r.phone \|\|= ... falsy
if r.get("notes"): r["notes"] = r["notes"].strip() r.notes &&= r.notes.trim() truthy

The hours take ??= because the form sends a blank number box as null, and an existing number, even 0, should stay. The phone takes ||= because the form sends a blank text box as "". Here are all three lines applied to the five requests:

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.