In this lesson, you ported the type check in describe() that says where each station is. Python
checks the location with isinstance(location, dict): a dict gives the latitude and longitude,
and anything else gives no GPS. Orchard’s GPS is off, so its location is None, and Python
prints no GPS on orchard’s line.
- JavaScript has no
dictclass to test against. Its everyday type check is thetypeofoperator, which names a value’s type as a string. A line-by-line port,typeof location === "object", declaresplacewithletbefore theif, because, unlike in Python, a name declared inside the braces, withletorconst, wouldn’t outlive them. - Orchard’s location is
null, and the port prints three lines, then stops withTypeError: Cannot read properties of null (reading 'lat'). typeof nullis"object", a fossil from JavaScript’s first engine in 1995, which storednullas all zeros, the type tag for objects. A later proposal to fix it was turned down because it would break existing pages. In Python,Nonehas a type of its own, soisinstance(None, dict)isFalse.- Each primitive type has its own name:
"string","number","boolean","undefined", and the rarer bigint and symbol.nullbreaks the pattern. A function gives"function", and every other object, an array too, gives"object". typeofdoesn’t throw for a name that was never declared. If you test for a missing value withtypeof x === "undefined", a misspelled name passes silently, where Python raisesNameError. Compare the value with=== undefined, and a typo stops with aReferenceError.- The fix pairs
typeofwith the question it can’t answer:location !== null && typeof location === "object". Like Python’sand,&&stops at the first false part. Write thenulltest first, as a habit, so the tests after it can rely on a real value. An array still gives"object", where Python’sisinstance()already saysFalsefor a list, so if a location could arrive as a pair of numbers, add&& !Array.isArray(location). typeofanswers which basic type a value has.NaN, short for not a number, is Python’smath.nan, a number in both languages, sotypeof NaNis"number". The difference is thatNumber("n/a")givesNaNsilently, where Python’sfloat("n/a")raises aValueError. A number check istypeof temp === "number" && !Number.isNaN(temp), which isfalsefor orchard’s temperature, sinceNumber.isNaN(temp)istrue.math.isnan()becomesNumber.isNaN(): JavaScript’sMath, its version of themathmodule, has noisNaN(). The globalisNaN()converts its argument first, so it treats an empty string as a number:isNaN("")isfalse.
Here are the fixed place lines in a small function, run on orchard’s reading:
function placeOf(reading) {
const location = reading.location;
let place;
if (location !== null && typeof location === "object") {
place = `at ${location.lat}, ${location.lon}`;
} else {
place = "no GPS";
}
return place;
}
console.log(placeOf({ station: "orchard", location: null }));
Orchard’s place comes out as Python’s does: