Giving Settings a JavaScript Protocol

Your settings audit now reads, validates, and refuses to lie about a fixed identifier. Whoever consults the audit report wants an object that lets them loop over the setting names, level and label, and identifies itself in a diagnostic.

In Python, a small class with __iter__() covers the loop, and its default repr names the class. Here you’ll meet the keys JavaScript uses for the same jobs and see why a proxy must pass them through untouched.

Make the Names Iterable With Symbol.iterator

The Python version of the setting names is a class whose __iter__() yields each name:

Language: Python
class SettingNames:
    def __iter__(self):
        yield "level"
        yield "label"

names = SettingNames()
print(list(names), names)

list() finds __iter__() by name, and print() shows the default repr, which names the class. The address varies by run:

Language: Program Output
['level', 'label'] <__main__.SettingNames object at 0x7f3cd682cd70>

JavaScript has no dunder names. The protocol keys in this lesson are well-known symbols on Symbol itself: symbols the language created once and saved, so for...of and spread always look for the same symbol. Symbol.iterator is one. Symbol.toPrimitive, which controls how an object turns into a primitive such as a number or a string, is another.

Here’s names as a plain iterable object. The square brackets make a computed key: the symbol itself becomes the key. The star in front marks a generator method, which pauses at each yield like a Python generator:

Language: JavaScript
const names = {
  *[Symbol.iterator]() {
    yield "level";
    yield "label";
  },
};

console.log([...names]);
for (const name of names) {
  console.log(name);
}

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.