Choosing a Protocol's Meaning

The drilling kit now loops over its tools because it answers the Symbol.iterator hook the way the Python kit answers __iter__(). With one protocol ported, it’s tempting to reach for the rest of Python’s dunder methods and look for a JavaScript name for each.

JavaScript has no such table. Some Python protocols become one shared hook, some have no hook at all, and one hook has no Python counterpart. In this lesson, you’ll see which hooks a kit should answer and why a hook is worth adding only when its meaning is clear.

Map Python’s Protocols to JavaScript Hooks

Python gives many language operations their own dunder method. JavaScript keeps a short list of built-in symbols, called well-known symbols, and each one has its own contract. This table maps the protocols a kit might touch:

Python JavaScript
__iter__() [Symbol.iterator]()
__str__() an ordinary toString() method
__int__(), __float__() one [Symbol.toPrimitive](hint) for every conversion to a primitive
__add__(), __lt__() no hook: operators convert to primitives first
__len__() no hook: an explicit property or method
no counterpart [Symbol.toStringTag]

Your __str__() ports to a plain toString() method. The third row works differently. When a class defines Symbol.toPrimitive, every conversion to a primitive goes through that one method, ahead of any toString(). The method receives a hint saying what the caller wants. Here’s the familiar library credit, recording the incoming hints:

Language: JavaScript
const hints = [];

class Credit {
  [Symbol.toPrimitive](hint) {
    hints.push(hint);
    if (hint === "string") {
      return "3 credits";
    }
    return 3;
  }
}

const credit = new Credit();
console.log(String(credit), Number(credit), credit + 2);
console.log(hints);

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

Become a Member to join the conversation.