Picking a Value With || and &&

Maya Okafor wants the Millbrook Community Center for a party. Her booking request leaves the rooms unticked, so Nadia’s script should book the hall and charge her for three hours. As you move Python’s default expression to JavaScript, you need to preserve both the room selection and the correct charge.

You’ll port that default and the notes cleanup without losing the values the script needs. Start with what the logical operators actually give back when you use them outside a condition.

Pick an Operand

An operand is a value an operator works on. Python’s or and and return one of their operands, and JavaScript’s || and && do the same. Truthy values count as true in a condition, while falsy values count as false.

Python can select strings and numbers directly:

Language: Python
print("Ada" or "Grace")
print("" or "Grace")
print("Ada" and "Grace")
print(0 and "Grace")

JavaScript makes the same selections with its logical operators:

Language: JavaScript
console.log("Ada" || "Grace");
console.log("" || "Grace");
console.log("Ada" && "Grace");
console.log(0 && "Grace");

Both programs print the selected values:

Language: Program Output
Ada
Grace
Grace
0

For a || b, a truthy a is the result. Otherwise, the result is b. For a && b, a falsy a is the result. Otherwise, it’s b. Neither operator converts the selected value to a Boolean.

If later booking code needs a true/false flag for whether a room label is present, convert the selected string explicitly. Python’s "hall" or "studio" selects "hall", while bool("hall") returns True. JavaScript’s "hall" || "studio" also selects "hall", while Boolean("hall") returns true. Use the selected string for the confirmation’s room label and the Boolean for a flag.

Default the Room List

The operator’s selection rule carries over, but the two languages don’t always agree about truthiness. Maya’s empty rooms list is where that difference affects a booking. These snippets use only the fields needed for her confirmation.

In the course’s booking data, rooms is always an array of known room names: "hall", "studio", or "kitchen". It can be empty when no rooms are ticked.

Python’s room default gives Nadia a hall to price:

Language: Python
DEFAULT_ROOM = "hall"
RATES = {"hall": 30, "studio": 18, "kitchen": 12}
maya = {"id": 102, "name": "Maya Okafor", "rooms": [],
        "hours": 3}
rooms = maya["rooms"] or [DEFAULT_ROOM]
cost = sum(RATES[room] for room in rooms) * maya["hours"]
print(f'{maya["id"]} {maya["name"]}: '
      f'{" and ".join(rooms)}, {maya["hours"]} hours, '
      f'${cost:.2f}')

Run the Python snippet to see the expected booking:

Language: Program Output
102 Maya Okafor: hall, 3 hours, $90.00

In JavaScript, JSON.parse() turns the form’s JSON text into data. A for...of loop visits each selected room, and += adds its hourly rate to the total. Before running this direct port, predict the room and price it’ll print:

Language: JavaScript
const DEFAULT_ROOM = "hall";
const RATES = { hall: 30, studio: 18, kitchen: 12 };
const maya = JSON.parse(
  '{"id":102,"name":"Maya Okafor","rooms":[],"hours":3}'
);
const rooms = maya.rooms || [DEFAULT_ROOM];
let hourlyRate = 0;
for (const room of rooms) {
  hourlyRate += RATES[room];
}
const cost = hourlyRate * maya.hours;
console.log(
  `${maya.id} ${maya.name}: ${rooms.join(" and ")}, ` +
  `${maya.hours} hours, $${cost.toFixed(2)}`
);

The port runs successfully and prints this confirmation:

Language: Program Output
102 Maya Okafor: , 3 hours, $0.00

There’s no room before the comma, and the price is zero. Every JavaScript array is truthy, including an empty one, so testing an array itself doesn’t tell you whether it contains anything. Here, || selects maya.rooms and never reaches the hall default. The loop has no room to visit, leaving the hourly rate at zero.

Ask about the number of rooms instead. The .length > 0 check tests for entries, and the conditional operator picks the expression after ? when that check succeeds, or the expression after : otherwise. Replace the rooms declaration with this version, shown with its data so you can run it separately:

Language: JavaScript
const DEFAULT_ROOM = "hall";
const maya = JSON.parse('{"rooms":[]}');
const rooms = maya.rooms.length > 0
  ? maya.rooms
  : [DEFAULT_ROOM];
console.log(rooms);

The room list now contains the default:

Language: Program Output
[ 'hall' ]

Using that declaration in the pricing snippet restores Python’s hall booking and ninety-dollar charge. For a display label alone, maya.rooms.join(" and ") || "hall" works like Python’s " and ".join(maya["rooms"]) or "hall", because the empty joined string is falsy in both languages. Another difference to remember: JavaScript’s NaN, a numeric value meaning not a number, is falsy, while Python’s float("nan") is truthy.

Clean Notes Only When Present

The confirmation also needs the choir’s padded note trimmed. Short-circuiting means skipping the right operand when the left operand has already settled the result. This lets && protect an operation on a value that might be missing.

In this booking data, notes is a string when supplied, and the property can be omitted. The guard below handles an empty string or a missing note. It doesn’t check the value’s type.

Python can guard .strip() with and:

Language: Python
choir = {"notes": "  Piano tuned, please  "}
maya = {"notes": ""}
yoga = {}
for request in [choir, maya, yoga]:
    notes = request.get("notes")
    print(repr(notes and notes.strip()))

Python keeps the empty string and returns None for the missing note:

Language: Program Output
'Piano tuned, please'
''
None

In JavaScript, a missing property gives undefined, and .trim() removes surrounding whitespace. Use && to call it only when there’s a truthy note:

Language: JavaScript
const choir = JSON.parse(
  '{"notes":"  Piano tuned, please  "}'
);
const maya = JSON.parse('{"notes":""}');
const yoga = JSON.parse('{}');
console.log(choir.notes && choir.notes.trim());
console.log(maya.notes && maya.notes.trim());
console.log(yoga.notes && yoga.notes.trim());

The middle output line is blank because the result is an empty string:

Language: Program Output
Piano tuned, please

undefined

For the choir, && reaches .trim() and returns its result. For Maya and the yoga class, it returns the left operand without calling .trim(). The same stopping rule lets || skip its right operand when the left is truthy. Choose the condition that matches the data, then let the operator select the value.

In the next lesson, Choosing Between || and ??, you’ll port the phone and deposit defaults and decide which operator fits each field.

Become a Member to join the conversation.