Picking a Value With || and &&

Sam Ortiz’s request from last month came out of the port with no room and a price of $0.00. This week, Maya Okafor’s party request, 102, leaves the rooms unchecked too. Nadia’s Python script books the hall for Maya with rooms = r["rooms"] or [DEFAULT_ROOM], and the port has to do the same. Most of how or picks a value carries over, so start there.

Pick an Operand

JavaScript’s || and && return one of their operands, as Python’s or and and do, and skip the right side once the left side settles the answer. The expressions map one to one:

Python JavaScript
a or b a \|\| b
a and b a && b
bool(x) Boolean(x)

Use Boolean(), or the !!x shorthand you’ll also see, only when you need a real true or false. Expect it to disagree with bool() on a few values, as the next section shows. The four expressions below give the same answers as in Python:

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

JavaScript prints the operand each operator settled on:

Language: Program Output
Ada
Grace
Grace
0

Skipping the right side makes && a guard. In JavaScript, a missing property reads as undefined, and .trim() does what Python’s .strip() does with no argument. This guard trims only the notes that have text:

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

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

Language: Program Output
Piano tuned, please

undefined

In Python, you’d use yoga.get("notes") to read the yoga class’s missing note, and .get() gives None. JavaScript reads it as undefined, and && hands that back. When the only worry is a missing property, choir.notes?.trim() is the usual guard, and && fits when any falsy value should stop the call. The selection rules match, but the list of falsy values doesn’t.

Default the Room List

Maya’s empty room list is where that matters. Here’s the Python line, run on her request:

Language: Python
DEFAULT_ROOM = "hall"
maya = {"id": 102, "name": "Maya Okafor", "rooms": [],
        "hours": 3}
rooms = maya["rooms"] or [DEFAULT_ROOM]
print(rooms)

Python’s empty list is falsy, so or moves on to the default and prints ['hall']. The port swaps or for || and adds up the hourly rates with for...of and +=. Predict the confirmation line before you run it:

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 without an error and prints this:

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

Nadia’s Python script, which adds up the same rates, prints 102 Maya Okafor: hall, 3 hours, $90.00. In JavaScript, every array is truthy, empty or not, so || hands back Maya’s empty array. The loop has no room to visit, and the rate stays at zero.

In JavaScript, check whether the array has any rooms. Every request from the form has a rooms array, so use .length > 0 with the conditional operator, condition ? ifTrue : ifFalse:

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

With that line, the rooms array holds the default:

Language: Program Output
[ 'hall' ]

The confirmation line from before now picks up the hall and prints $90.00 again.

JavaScript’s falsy values are false, 0, "", null, undefined, and NaN, and every other value is truthy. Keep that list in mind whenever ||, &&, or an if tests a value:

  • Empty arrays and objects are truthy, so if (rows) takes the “has data” branch for []. Test rows.length instead.
  • Empty strings are falsy in both languages, so maya.rooms.join(" and ") || "hall" gives hall as Python’s version does. That only fills in the label. The rooms array stays empty, so the rate is still zero.
  • NaN is falsy in JavaScript, while Python’s float("nan") is truthy. So NaN || 2 gives 2.

Use || for a default only when every falsy value means “nothing here,” and check .length for an array. In the next lesson, Choosing Between || and ??, you’ll port the phone and deposit lines and pick the right default operator for each field.

Become a Member to join the conversation.