Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Checking Types When typeof Says "object"

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 dict class to test against. Its everyday type check is the typeof operator, which names a value’s type as a string. A line-by-line port, typeof location === "object", declares place with let before the if, because, unlike in Python, a name declared inside the braces, with let or const, wouldn’t outlive them.
  • Orchard’s location is null, and the port prints three lines, then stops with TypeError: Cannot read properties of null (reading 'lat').
  • typeof null is "object", a fossil from JavaScript’s first engine in 1995, which stored null as all zeros, the type tag for objects. A later proposal to fix it was turned down because it would break existing pages. In Python, None has a type of its own, so isinstance(None, dict) is False.
  • Each primitive type has its own name: "string", "number", "boolean", "undefined", and the rarer bigint and symbol. null breaks the pattern. A function gives "function", and every other object, an array too, gives "object".
  • typeof doesn’t throw for a name that was never declared. If you test for a missing value with typeof x === "undefined", a misspelled name passes silently, where Python raises NameError. Compare the value with === undefined, and a typo stops with a ReferenceError.
  • The fix pairs typeof with the question it can’t answer: location !== null && typeof location === "object". Like Python’s and, && stops at the first false part. Write the null test first, as a habit, so the tests after it can rely on a real value. An array still gives "object", where Python’s isinstance() already says False for a list, so if a location could arrive as a pair of numbers, add && !Array.isArray(location).
  • typeof answers which basic type a value has. NaN, short for not a number, is Python’s math.nan, a number in both languages, so typeof NaN is "number". The difference is that Number("n/a") gives NaN silently, where Python’s float("n/a") raises a ValueError. A number check is typeof temp === "number" && !Number.isNaN(temp), which is false for orchard’s temperature, since Number.isNaN(temp) is true.
  • math.isnan() becomes Number.isNaN(): JavaScript’s Math, its version of the math module, has no isNaN(). The global isNaN() converts its argument first, so it treats an empty string as a number: isNaN("") is false.

Here are the fixed place lines in a small function, run on orchard’s reading:

Language: JavaScript
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:

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

00:00 In this lesson, you’ll port the type check that says where each station is. In describe(), Python asks isinstance() whether the location is a dict.

00:10 A dict gives the latitude and longitude, and anything else gives no GPS.

00:17 Orchard’s GPS is off, so None is its location. Python prints no GPS on orchard’s line. The check looks like it ports line by line, but it doesn’t carry over the way it looks.

00:32 In the port, a const carries the location over. JavaScript has no dict class to test against. Its everyday type check is the typeof operator, which names a value’s type as a string.

00:45 An object, like ridge’s location, gives “object”. So the port asks whether typeof location is “object”. A let line declares place above the if, because, unlike in Python, a name declared inside the braces would end with them.

01:02 The rest becomes a template literal and a string.

01:07 Orchard’s location is null, standing in for Python’s None here. What does the port print for orchard? Your turn: pause the video and predict.

01:22 JavaScript prints ridge, mill and the skipped resend. Then it stops with a TypeError on the place line. It can’t read properties of null, so orchard’s location got past the check.

01:38 typeof null gives “object”. So orchard’s null passed the check, and the next line read lat from it. In Python, None has a type of its own, so isinstance() says False.

01:53 JavaScript’s answer is a fossil from its first version, in 1995. That engine stored null as all zeros, and zero was the type tag for objects.

02:04 A fix proposed years later was turned down, because it would break existing web pages.

02:10 Here’s every answer typeof gives. Each primitive type has its own name: string, number, boolean, undefined, and the rarer bigint and symbol.

02:22 null is the one primitive that breaks the pattern. A function gives “function”, and every other object, an array too, gives “object”. Watch out: typeof doesn’t throw for a name that was never declared.

02:36 So if you test for a missing value with typeof x === "undefined", a misspelled name passes silently, where Python raises a NameError right away.

02:48 Compare the value with === undefined, and a typo stops with a ReferenceError instead.

02:56 A JavaScript developer pairs typeof with the question it can’t answer. The new condition starts by ruling null out. Then && joins the typeof test, as Python’s and would.

03:10 For orchard, the first part is false, so && stops there and the if block never runs. Write the null test first, as a habit, so the tests after it can rely on a real value.

03:24 Run the port, and orchard’s line prints no GPS. All six lines match the Python check’s. An array still gives “object”, though, where Python’s dict check already says False for a list.

03:38 If a location could arrive as a pair of numbers, add Array.isArray() as a third test, with a ! in front.

03:49 typeof answers one question: which basic type a value has. Pair it with the question it can’t answer. For objects, rule out null, and for arrays, ask Array.isArray() too.

04:04 Watch out for numbers: orchard’s temperature is NaN, Python’s math.nan, short for not a number. It’s a number in both languages, so typeof says “number”.

04:16 But Number("n/a") gives NaN silently, where Python’s float() raises. Number.isNaN() catches orchard’s temperature, giving true.

04:27 So for numbers, add it with a ! in front. Watch out, too: math.isnan() becomes Number.isNaN(), because JavaScript’s Math, its version of the math module, has no isNaN() at all.

04:40 And the global isNaN() converts first, so it calls an empty string a number.

04:47 Next up is Checking an Object’s Class With instanceof, a text lesson. There, you’ll use instanceof to tell the time each reading was taken, a Date, apart from other objects, something typeof can’t do.

Become a Member to join the conversation.