In this lesson, you started porting the co-op’s Python check to JavaScript, with the line that
skips resent readings. In the 09:00 batch, the ridge station resent its reading over flaky Wi-Fi,
so the batch holds two separate dicts with the same fields. Python’s if reading in seen: compares
with ==, so the copy counts as seen, and the check prints 3 readings checked.
- A line-by-line port,
if (seen.includes(reading)) {, lets the resent reading through: JavaScript prints the ridge line twice, and the count says4 readings checked. - Python asks two questions:
==(do two objects hold the same contents?) andis(are they the same object?). For the two ridge dicts,==isTrueandisisFalse. - For objects, JavaScript’s
includes()compares the way===does, and===asks Python’sisquestion. The resent reading is a second object, so===givesfalse. JavaScript writes its booleans in lowercase,trueandfalse. - Names point at shared objects, as in Python: search for the first reading itself, and
includes()finds it. Comparing two readings with===or!==follows the same rule, so equal fields don’t make them the same object. - The fix is to decide what makes two readings the same, here the station and its sequence number,
and keep the names built from them, such as
ridge #1412, inseen, as a Python check could too. - Strings compare by value however they were built, so
"rid" + "ge" === "ridge"istrue. In Python, a string is an object, soiscould giveFalsefor equal text, and you compare with==. In JavaScript, there’s no identity question to ask of a string:===compares the characters. - Read
===as Python’s==for numbers, strings and booleans, and as Python’sisfor arrays and objects. Copying objects, and comparing every field of two whole objects, are a later topic.
Here’s the port’s loop with the fix in place. The field checks and each reading’s line are left out:
const seen = [];
let checked = 0;
for (const reading of batch) {
const name = `${reading.station} #${reading.seq}`;
if (seen.includes(name)) {
console.log(`Skipped resent ${name}`);
} else {
seen.push(name);
// ... reject bad fields, or print the line and count it
}
}
console.log(`${checked} readings checked`);
When you run the whole check with node readings-check.js, it prints the same six lines as the
Python check:
ridge #1412: 6.5°C, 0.2 mm rain, at 54.61, -3.05
mill #877: 7.4°C (unchanged), dry, at 54.58, -3.11
Skipped resent ridge #1412
orchard #2290: no temperature (unchanged), no rain data, no GPS
Rejected school #96: bad fields
3 readings checked
Next up is the text lesson Why Strings and Numbers Can’t Change. There, you’ll see why === can
compare strings by value, and how a string can have methods at all.