Loading video player…

Following Ordinary Object Conversion

Following Ordinary Object Conversion

In this lesson, you ported the Reading class of Mina’s gallery display, whose screen shows the label 21 C, from Python to JavaScript and followed how JavaScript turns the reading into text or a number. In Python, str() and an f-string use __str__() and give 21 C, and float() uses __float__() and gives 21.0. But reading + 1 raises a TypeError: Python’s arithmetic operators, such as + and *, never fall back to __float__().

  • In the port, toString() takes over from __str__(), and valueOf() from __float__(): valueOf() returns a primitive that stands in for the object, here the number 21.
  • String(reading) and `${reading}` print 21 C, and Number(reading) prints 21. reading + 1 gives 22 and reading * 2 gives 42: JavaScript calls valueOf() for you when the reading sits beside an arithmetic operator such as + or *.
  • Jonah’s label shortcut, reading + "", prints 21, not 21 C. A log line in each method shows why: String() and the template literal run toString(), while reading + "", Number(), reading + 1 and reading * 2 run valueOf().
  • To get a primitive from an object, JavaScript runs an internal step the specification calls ToPrimitive. It gets a hint: string from String() and template literals tries toString() first; number from Number() and * tries valueOf() first; default from + acts like number for ordinary objects.
  • Python’s __add__() can redefine + for a class; valueOf() can’t. It only supplies the primitive that ordinary addition then uses.
  • A hint sets an order, not a single method. If the first method returns an object, JavaScript tries the other one: a test object whose valueOf() returns {} and whose toString() returns "21" logs valueOf, then toString, and Number() gives 21. If both return objects, JavaScript throws TypeError: Cannot convert object to primitive value.
  • The default Object.prototype.valueOf() returns the object itself, so objects using that default fall through to toString().
  • A Date is a built-in exception: its default hint acts like string, so + joins its text.

Here’s Mina’s display line, converting on purpose, with the Python version first:

Language: Python
class Reading:
    def __init__(self, celsius):
        self.celsius = celsius

    def __float__(self):
        return float(self.celsius)

    def __str__(self):
        return f"{self.celsius} C"

reading = Reading(21)
next_celsius = float(reading) + 1
print(f"Reading: {reading}; next: {next_celsius:g} C")

The JavaScript port builds the label with a template literal and converts with Number() before adding one:

Language: JavaScript
class Reading {
  constructor(celsius) {
    this.celsius = celsius;
  }

  valueOf() {
    return this.celsius;
  }

  toString() {
    return `${this.celsius} C`;
  }
}

const reading = new Reading(21);
const nextCelsius = Number(reading) + 1;
console.log(`Reading: ${reading}; next: ${nextCelsius} C`);

Python’s :g drops the point zero from 22.0, so both programs print the same line:

Language: Program Output
Reading: 21 C; next: 22 C

Convert at the boundary: String() or a template literal for text, Number() for numbers, and don’t let + pick a method for you. A later lesson shows how a class can answer each hint itself.

Next up is the text lesson Reading the Spec’s Conversion Steps. There, you’ll trace the steps that turn missing readings and arrays of notes into strings, numbers, and Booleans.

00:00 In this lesson, you’ll follow how JavaScript turns an object into text or a number. Mina’s gallery display is moving from Python to JavaScript, and its screen shows the label 21 C.

00:14 Its Reading class stores a Celsius temperature. __float__() returns the number, and __str__() returns the label. str() and the f-string give 21 C.

00:27 float() gives 21.0.

00:30 Beside a plus sign, the reading raises a TypeError. Python’s arithmetic operators never fall back to __float__() for you.

00:41 In the JavaScript port, the constructor plays the part of __init__(), with this for Python’s self parameter.

00:48 For a number, JavaScript looks for a method named valueOf() on the object. It returns a primitive to stand in for the object. toString() takes over from __str__(), with a template literal, JavaScript’s f-string.

01:04 Each console.log() call prints a line. String() and the template literal print 21 C. Number(), the closest thing to float(), gives 21, without the point zero.

01:17 Plus one gives 22, and times two gives 42.

01:23 Unlike Python, JavaScript called valueOf() for you, because of the arithmetic operators.

01:30 Mina’s teammate Jonah has written JavaScript for years. For the label, he adds a common shortcut: the reading plus an empty string. Plus adds numbers but joins strings, so Jonah expects joining nothing to leave the label.

01:47 In Python, str() and f-strings share one method for text. String() and the template literal gave 21 C. What does Jonah’s line print?

01:57 Your turn: pause the video and predict.

02:06 It prints 21, with no C. The display would show 21 instead of 21 C. JavaScript didn’t ask toString() this time.

02:19 To see which method runs, add a line that logs each method’s name, and run the file again. String() and the template literal each run toString() and print the label.

02:30 Jonah’s line runs valueOf() instead. So do Number(), plus one and times two. The method JavaScript calls depends on how you asked.

02:43 To get a primitive from an object, JavaScript runs ToPrimitive, an internal step named in the language specification. The step gets a hint saying what kind of value the code wants.

02:56 String() and template literals pass string, so toString() goes first. Number() and the times sign pass number, so valueOf() goes first.

03:07 Plus passes default, since it can’t tell yet whether it’ll add or join. Ordinary objects like the reading treat default like number. So valueOf() returns 21, and plus joins it with the empty string.

03:22 Python’s __add__() can redefine plus, but valueOf() can’t: it only supplies a primitive.

03:30 A hint sets an order, not a single method. If the first method returns an object, JavaScript tries the other one. The default Object.prototype.valueOf() returns the object itself, so objects using that default fall through to toString().

03:49 This test object’s valueOf() returns an empty object, and its toString() returns the text 21. Number() logs valueOf, then toString, and gives the number 21.

04:02 If both methods returned objects, JavaScript would throw a TypeError. A built-in exception: a Date treats default like string, so plus joins its text.

04:16 The log lines and test lines come out. Number() converts the reading before adding one, as Python calls float() first. The display’s line builds the label with a template literal, which asks for text.

04:29 Python’s :g drops the point zero, so both programs print the same line. So convert at the boundary: String() or a template literal for text, Number() for numbers.

04:43 Don’t let plus pick a method for you; a later lesson shows how a class can answer each hint itself. Next up is the text lesson Reading the Spec’s Conversion Steps.

Become a Member to join the conversation.