Please support this book: buy it or donate

25. Single objects



In this book, JavaScript’s style of object-oriented programming (OOP) is introduced in four steps. This chapter covers step 1, the next chapter covers steps 2–4. The steps are (fig. 7):

  • Single objects: How do objects, JavaScript’s basic OOP building blocks, work in isolation?
  • Prototype chains: Each object has a chain of zero or more prototype objects. Prototypes are JavaScript’s core inheritance mechanism.
  • Classes: JavaScript’s classes are factories for objects. The relationship between a class and its instances is based on prototypal inheritance.
  • Subclassing: The relationship between a subclass and its superclass is also based on prototypal inheritance.
    Figure 7: This book introduces object-oriented programming in JavaScript in four steps.
    Figure 7: This book introduces object-oriented programming in JavaScript in four steps.

25.1. The two roles of objects in JavaScript

In JavaScript, an object is a set of key-value entries that are called properties.

Objects play two roles in JavaScript:

  • Records: Objects-as-records have a fixed number of properties, whose keys are known at development time. Their values can have different types. This way of using objects is covered first in this chapter.

  • Dictionaries: Objects-as-dictionaries have a variable number of properties, whose keys are not known at development time. All of their values have the same type. It is usually better to use Maps as dictionaries than objects (which is covered later in this chapter).

25.2. Objects as records

25.2.1. Object literals: properties

Objects as records are created via so-called object literals. Object literals are a stand-out feature of JavaScript: they allow you to directly create objects. No need for classes! This is an example:

  1. const jane = {
  2. first: 'Jane',
  3. last: 'Doe', // optional trailing comma
  4. };

In the example, we created an object via an object literal, which starts and ends with curly braces {}. Inside it, we defined two properties (key-value entries):

  • The first property has the key first and the value 'Jane'.
  • The second property has the key last and the value 'Doe'.
    If they are written this way, property keys must follow the rules of JavaScript variable names, with the exception that reserved words are allowed.

The properties are accessed as follows:

  1. assert.equal(jane.first, 'Jane'); // get property .first
  2. jane.first = 'John'; // set property .first
  3. assert.equal(jane.first, 'John');

25.2.2. Object literals: property value shorthands

Whenever the value of a property is defined via a variable name and that name is the same as the key, you can omit the key.

  1. const x = 4;
  2. const y = 1;
  3. assert.deepEqual(
  4. { x, y },
  5. { x: x, y: y }
  6. );

25.2.3. Terminology: property keys, property names, property symbols

Given that property keys can be strings and symbols, the following distinction is made:

  • If a property key is a string, it is also called a property name.
  • If a property key is a symbol, it is also called a property symbol.
    This terminology is used in the JavaScript standard library (“own” means “not inherited” and is explained in the next chapter):

  • Object.keys(obj): returns all property keys of obj

  • Object.getOwnPropertyNames(obj)
  • Object.getOwnPropertySymbols(obj)

25.2.4. Getting properties

This is how you get (read) a property:

  1. obj.propKey

If obj does not have a property whose key is propKey, this expression evaluates to undefined:

  1. const obj = {};
  2. assert.equal(obj.propKey, undefined);

25.2.5. Setting properties

This is how you set (write to) a property:

  1. obj.propKey = value;

If obj already has a property whose key is propKey, this statement changes that property. Otherwise, it creates a new property:

  1. const obj = {};
  2. assert.deepEqual(
  3. Object.keys(obj), []);
  4. obj.propKey = 123;
  5. assert.deepEqual(
  6. Object.keys(obj), ['propKey']);

25.2.6. Object literals: methods

The following code shows how to create the method .describe() via an object literal:

  1. const jane = {
  2. first: 'Jane', // data property
  3. says(text) { // method
  4. return `${this.first} says “${text}”`; // (A)
  5. }, // comma as separator (optional at end)
  6. };
  7. assert.equal(jane.says('hello'), 'Jane says “hello”');

During the method call jane.says('hello'), jane is called the receiver of the method call and assigned to the special variable this. That enables method .says() to access the sibling property .first in line A.

25.2.7. Object literals: accessors

There are two kinds of accessors in JavaScript:

  • A getter is a method that is invoked by getting (reading) a property.
  • A setter is a method that is invoked by setting (writing) a property.
25.2.7.1. Getters

A getter is created by prefixing a method definition with the keyword get:

  1. const jane = {
  2. first: 'Jane',
  3. last: 'Doe',
  4. get full() {
  5. return `${this.first} ${this.last}`;
  6. },
  7. };
  8. assert.equal(jane.full, 'Jane Doe');
  9. jane.first = 'John';
  10. assert.equal(jane.full, 'John Doe');
25.2.7.2. Setters

A setter is created by prefixing a method definition with the keyword set:

  1. const jane = {
  2. first: 'Jane',
  3. last: 'Doe',
  4. set full(fullName) {
  5. const parts = fullName.split(' ');
  6. this.first = parts[0];
  7. this.last = parts[1];
  8. },
  9. };
  10. jane.full = 'Richard Roe';
  11. assert.equal(jane.first, 'Richard');
  12. assert.equal(jane.last, 'Roe');

25.3. Spreading into object literals (…)

We have already seen spreading () being used in function calls, where it turns the contents of an iterable into arguments.

Inside an object literal, a spread property adds the properties of another object to the current one:

  1. > const obj = {foo: 1, bar: 2};
  2. > {...obj, baz: 3}
  3. { foo: 1, bar: 2, baz: 3 }

If property keys clash, the property that is mentioned last “wins”:

  1. > const obj = {foo: 1, bar: 2, baz: 3};
  2. > {...obj, foo: true}
  3. { foo: true, bar: 2, baz: 3 }
  4. > {foo: true, ...obj}
  5. { foo: 1, bar: 2, baz: 3 }

25.3.1. Use case for spreading: copying objects

You can use spread to create a copy of an object original:

  1. const copy = {...original};

Caveat – copying is shallow: copy is a fresh object with a copy of all properties (key-value pairs) of original. But if property values are objects, then those are not copied; they are shared between original and copy. The following code demonstrates what that means.

  1. const original = { a: 1, b: {foo: true} };
  2. const copy = {...original};
  3. // The first level is a true copy:
  4. assert.deepEqual(
  5. copy, { a: 1, b: {foo: true} });
  6. original.a = 2;
  7. assert.deepEqual(
  8. copy, { a: 1, b: {foo: true} }); // no change
  9. // Deeper levels are not copied:
  10. original.b.foo = false;
  11. // The value of property `b` is shared
  12. // between original and copy.
  13. assert.deepEqual(
  14. copy, { a: 1, b: {foo: false} });

25.3.2. Use case for spreading: default values for missing properties

If one of the inputs of your code is an object with data, you can make properties optional if you specify default values for them. One technique for doing so is via an object whose properties contain the default values. In the following example, that object is DEFAULTS:

  1. const DEFAULTS = {foo: 'a', bar: 'b'};
  2. const providedData = {foo: 1};
  3. const allData = {...DEFAULTS, ...providedData};
  4. assert.deepEqual(allData, {foo: 1, bar: 'b'});

The result, the object allData, is created by creating a copy of DEFAULTS and overriding its properties with those of providedData.

But you don’t need an object to specify the default values, you can also specify them inside the object literal, individually:

  1. const providedData = {foo: 1};
  2. const allData = {foo: 'a', bar: 'b', ...providedData};
  3. assert.deepEqual(allData, {foo: 1, bar: 'b'});

25.3.3. Use case for spreading: non-destructively changing properties

So far, we have encountered one way of changing a property of an object: We set it and mutate the object. That is, this way of changing a property is destructive

With spreading, you can change a property non-destructively: You make a copy of the object where the property has a different value.

For example, this code non-destructively updates property .foo:

  1. const obj = {foo: 'a', bar: 'b'};
  2. const updatedObj = {...obj, foo: 1};
  3. assert.deepEqual(updatedObj, {foo: 1, bar: 'b'});

25.4. Methods

25.4.1. Methods are properties whose values are functions

Let’s revisit the example that was used to introduce methods:

  1. const jane = {
  2. first: 'Jane',
  3. says(text) {
  4. return `${this.first} says “${text}”`;
  5. },
  6. };

Somewhat surprisingly, methods are functions:

  1. assert.equal(typeof jane.says, 'function');

Why is that? Remember that, in the chapter on callable entities, we learned that ordinary functions play several roles. Method is one of those roles. Therefore, under the hood, jane roughly looks as follows.

  1. const jane = {
  2. first: 'Jane',
  3. says: function (text) {
  4. return `${this.first} says “${text}”`;
  5. },
  6. };

25.4.2. .call(): explicit parameter this

Remember that each function someFunc is also an object and therefore has methods. One such method is .call() – it lets you call functions while specifying this explicitly:

  1. someFunc.call(thisValue, arg1, arg2, arg3);
25.4.2.1. Methods and .call()

If you make a method call, this is always an implicit parameter:

  1. const obj = {
  2. method(x) {
  3. assert.equal(this, obj); // implicit parameter
  4. assert.equal(x, 'a');
  5. },
  6. };
  7. obj.method('a');
  8. // Equivalent:
  9. obj.method.call(obj, 'a');

As an aside, that means that there are actually two different dot operators:

  • One for accessing properties: obj.prop
  • One for making method calls: obj.prop()
    They are different in that (2) is not just (1), followed by the function call operator (). Instead, (2) additionally specifies a value for this (as shown in the previous example).
25.4.2.2. Functions and .call()

However, this is also an implicit parameter if you function-call an ordinary function:

  1. function func(x) {
  2. assert.equal(this, undefined); // implicit parameter
  3. assert.equal(x, 'a');
  4. }
  5. func('a');
  6. // Equivalent:
  7. func.call(undefined, 'a');

That is, during a function call, ordinary functions have a this, but it is set to undefined, which indicates that it doesn’t really have a purpose here.

Next, we’ll examine the pitfalls of using this. Before we can do that, we need one more tool: the method .bind() of functions.

25.4.3. .bind(): pre-filling this and parameters of functions

.bind() is another method of function objects. This method is invoked as follows.

  1. const boundFunc = someFunc.bind(thisValue, arg1, arg2, arg3);

.bind() returns a new function boundFunc(). Calling that function invokes someFunc() with this set to thisValue and these parameters: arg1, arg2, arg3, followed by the parameters of boundFunc().

That is, the following two function calls are equivalent:

  1. boundFunc('a', 'b')
  2. someFunc.call(thisValue, arg1, arg2, arg3, 'a', 'b')

Another way of pre-filling this and parameters, is via an arrow function:

  1. const boundFunc2 = (...args) =>
  2. someFunc.call(thisValue, arg1, arg2, arg3, ...args);

Therefore, .bind() can be implemented as a real function as follows:

  1. function bind(func, thisValue, ...boundArgs) {
  2. return (...args) =>
  3. func.call(thisValue, ...boundArgs, ...args);
  4. }
25.4.3.1. Example: binding a real function

Using .bind() for real functions is somewhat unintuitive, because you have to provide a value for this. That value is usually undefined, mirroring what happens during function calls.

In the following example, we create add8(), a function that has one parameter, by binding the first parameter of add() to 8.

  1. function add(x, y) {
  2. return x + y;
  3. }
  4. const add8 = add.bind(undefined, 8);
  5. assert.equal(add8(1), 9);
25.4.3.2. Example: binding a method

In the following code, we turn method .says() into the stand-alone function func():

  1. const jane = {
  2. first: 'Jane',
  3. says(text) {
  4. return `${this.first} says “${text}”`; // (A)
  5. },
  6. };
  7. const func = jane.says.bind(jane, 'hello');
  8. assert.equal(func(), 'Jane says “hello”');

Setting this to jane via .bind() is crucial here. Otherwise, func() wouldn’t work properly, because this is used in line A.

25.4.4. this pitfall: extracting methods

We now know quite a bit about functions and methods and are ready to take a look at the biggest pitfall involving methods and this: function-calling a method extracted from an object can fail if you are not careful.

In the following example, we fail when we extract method jane.says(), store it in the variable func and function-call func().

  1. const jane = {
  2. first: 'Jane',
  3. says(text) {
  4. return `${this.first} says “${text}”`;
  5. },
  6. };
  7. const func = jane.says; // extract the method
  8. assert.throws(
  9. () => func('hello'), // (A)
  10. {
  11. name: 'TypeError',
  12. message: "Cannot read property 'first' of undefined",
  13. });

The function call in line A is equivalent to:

  1. assert.throws(
  2. () => jane.says.call(undefined, 'hello'), // `this` is undefined!
  3. {
  4. name: 'TypeError',
  5. message: "Cannot read property 'first' of undefined",
  6. });

So how do we fix this? We need to use .bind() to extract method .says():

  1. const func2 = jane.says.bind(jane);
  2. assert.equal(func2('hello'), 'Jane says “hello”');

The .bind() ensures that this is always jane when we call func().

You can also use arrow functions to extract methods:

  1. const func3 = text => jane.says(text);
  2. assert.equal(func3('hello'), 'Jane says “hello”');
25.4.4.1. Example: extracting a method

The following is a simplified version of code that you may see in actual web development:

  1. class ClickHandler {
  2. constructor(elem) {
  3. elem.addEventListener('click', this.handleClick); // (A)
  4. }
  5. handleClick(event) {
  6. alert('Clicked!');
  7. }
  8. }

In line A, we don’t extract the method .handleClick() properly. Instead, we should do:

  1. elem.addEventListener('click', this.handleClick.bind(this));

25.4.5. this pitfall: accidentally shadowing this

Accidentally shadowing this is only an issue if you use ordinary functions.

Consider the following problem: When you are inside an ordinary function, you can’t access the this of the surrounding scope, because the ordinary function has its own this. In other words: a variable in an inner scope hides a variable in an outer scope. That is called shadowing. The following code is an example:

  1. const obj = {
  2. name: 'Jane',
  3. sayHiTo(friends) {
  4. return friends.map(
  5. function (friend) { // (A)
  6. return `${this.name} says hi to ${friend}`; // (B)
  7. });
  8. }
  9. };
  10. assert.throws(
  11. () => obj.sayHiTo(['Tarzan', 'Cheeta']),
  12. {
  13. name: 'TypeError',
  14. message: "Cannot read property 'name' of undefined",
  15. });

Why the error? The this in line B isn’t the this of .sayHiTo(), it is the this of the ordinary function starting in line B.

There are several ways to fix this. The easiest is to use an arrow function – which doesn’t have its own this, so shadowing is not an issue.

  1. const obj = {
  2. name: 'Jane',
  3. sayHiTo(friends) {
  4. return friends.map(
  5. (friend) => {
  6. return `${this.name} says hi to ${friend}`;
  7. });
  8. }
  9. };
  10. assert.deepEqual(
  11. obj.sayHiTo(['Tarzan', 'Cheeta']),
  12. ['Jane says hi to Tarzan', 'Jane says hi to Cheeta']);

25.4.6. Avoiding the pitfalls of this

We have seen two big this-related pitfalls:

“Avoid the keyword function”: Never use ordinary functions, only arrow functions (for real functions) and method definitions.

Let’s break down this rule:

  • If all real functions are arrow functions, the second pitfall can never occur.
  • Using method definitions means that you’ll only see this inside methods, which makes this feature less confusing.
    However, even though I don’t use (ordinary) function expressions, anymore, I do like function declarations syntactically. You can use them safely if you don’t refer to this inside them. The checking tool ESLint has a rule that helps with that.

Alas, there is no simple way around the first pitfall: Whenever you extract a method, you have to be careful and do it properly. For example, by binding this.

25.4.7. The value of this in various contexts

What is the value of this in various contexts?

Inside a callable entity, the value of this depends on how the callable entity is invoked and what kind of callable entity it is:

  • Function call:
    • Ordinary functions: this === undefined
    • Arrow functions: this is same as in surrounding scope (lexical this)
  • Method call: this is receiver of call
  • new: this refers to newly created instance
    You can also access this in all common top-level scopes:

  • <script> element: this === window

  • ES modules: this === undefined
  • CommonJS modules: this === module.exports
    However, I like to pretend that you can’t access this in top-level scopes, because top-level this is confusing and not that useful.

25.5. Objects as dictionaries

Objects work best as records. But before ES6, JavaScript did not have a data structure for dictionaries (ES6 brought Maps). Therefore, objects had to be used as dictionaries. As a consequence, keys had to be strings, but values could have arbitrary types.

We first look at features of objects that are related to dictionaries, but also occasionally useful for objects-as-records. This section concludes with tips for actually using objects as dictionaries (spoiler: avoid, use Maps if you can).

25.5.1. Arbitrary fixed strings as property keys

When going from objects-as-records to objects-as-dictionaries, one important change is that we must be able to use arbitrary strings as property keys. This subsection explains how to achieve that for fixed string keys. The next subsection explains how to dynamically compute arbitrary keys.

So far, we have only seen legal JavaScript identifiers as property keys (with the exception of symbols):

  1. const obj = {
  2. mustBeAnIdentifier: 123,
  3. };
  4. // Get property
  5. assert.equal(obj.mustBeAnIdentifier, 123);
  6. // Set property
  7. obj.mustBeAnIdentifier = 'abc';
  8. assert.equal(obj.mustBeAnIdentifier, 'abc');

Two techniques allow us to use arbitrary strings as property keys.

First – when creating property keys via object literals, we can quote property keys (with single or double quotes):

  1. const obj = {
  2. 'Can be any string!': 123,
  3. };

Second – when getting or setting properties, we can use square brackets with strings inside them:

  1. // Get property
  2. assert.equal(obj['Can be any string!'], 123);
  3. // Set property
  4. obj['Can be any string!'] = 'abc';
  5. assert.equal(obj['Can be any string!'], 'abc');

You can also quote the keys of methods:

  1. const obj = {
  2. 'A nice method'() {
  3. return 'Yes!';
  4. },
  5. };
  6. assert.equal(obj['A nice method'](), 'Yes!');

25.5.2. Computed property keys

So far, we were limited by what we could do with property keys inside object literals: They were always fixed and they were always strings. We can dynamically compute arbitrary keys if we put expressions in square brackets:

  1. const obj = {
  2. ['Hello world!']: true,
  3. ['f'+'o'+'o']: 123,
  4. [Symbol.toStringTag]: 'Goodbye', // (A)
  5. };
  6. assert.equal(obj['Hello world!'], true);
  7. assert.equal(obj.foo, 123);
  8. assert.equal(obj[Symbol.toStringTag], 'Goodbye');

The main use case for computed keys is having symbols as property keys (line A).

Note that the square brackets operator for getting and setting properties works with arbitrary expressions:

  1. assert.equal(obj['f'+'o'+'o'], 123);
  2. assert.equal(obj['==> foo'.slice(-3)], 123);

Methods can have computed property keys, too:

  1. const methodKey = Symbol();
  2. const obj = {
  3. [methodKey]() {
  4. return 'Yes!';
  5. },
  6. };
  7. assert.equal(obj[methodKey](), 'Yes!');

We are now switching back to fixed property keys, but you can always use square brackets if you need computed property keys.

25.5.3. The in operator: is there a property with a given key?

The in operator checks if an object has a property with a given key:

  1. const obj = {
  2. foo: 'abc',
  3. bar: false,
  4. };
  5. assert.equal('foo' in obj, true);
  6. assert.equal('unknownKey' in obj, false);
25.5.3.1. Checking if a property exists via truthiness

You can also use a truthiness check to determine if a property exists:

  1. assert.equal(
  2. obj.unknownKey ? 'exists' : 'does not exist',
  3. 'does not exist');
  4. assert.equal(
  5. obj.foo ? 'exists' : 'does not exist',
  6. 'exists');

The previous check works, because reading a non-existent property returns undefined, which is falsy. And because obj.foo is truthy.

There is, however, one important caveat: Truthiness checks fail if the property exists, but has a falsy value (undefined, null, false, 0, "", etc.):

  1. assert.equal(
  2. obj.bar ? 'exists' : 'does not exist',
  3. 'does not exist'); // should be: 'exists'

25.5.4. Deleting properties

You can delete properties via the delete operator:

  1. const obj = {
  2. foo: 123,
  3. };
  4. assert.deepEqual(Object.keys(obj), ['foo']);
  5. delete obj.foo;
  6. assert.deepEqual(Object.keys(obj), []);

25.5.5. Dictionary pitfalls

If you use plain objects (created via object literals) as dictionaries, you have to look out for two pitfalls.

The first pitfall is that the in operator also finds inherited properties:

  1. const dict = {};
  2. assert.equal('toString' in dict, true);

We want dict to be treated as empty, but the in operator detects the properties it inherits from its prototype, Object.prototype.

The second pitfall is that you can’t use the property key proto, because it has special powers (it sets the prototype of the object):

  1. const dict = {};
  2. dict['__proto__'] = 123;
  3. // No property was added to dict:
  4. assert.deepEqual(Object.keys(dict), []);

So how do we navigate around these pitfalls?

  • Whenever you can, use Maps. They are the best solution for dictionaries.

  • If you can’t: use a library for objects-as-dictionaries that does everything safely.

  • If you can’t: use an object without a prototype. That eliminates the two pitfalls in modern JavaScript.

  1. const dict = Object.create(null); // no prototype
  2. assert.equal('toString' in dict, false);
  3. dict['__proto__'] = 123;
  4. assert.deepEqual(Object.keys(dict), ['__proto__']);

25.5.6. Listing property keys

Table 19: Standard library methods for listing own (non-inherited) property keys. All of them return Arrays with strings and/or symbols.
enumerablenon-e.stringsymbol
Object.keys()
Object.getOwnPropertyNames()
Object.getOwnPropertySymbols()
Reflect.ownKeys()

Each of the methods in tbl. 19 returns an Array with the own property keys of the parameter. In the names of the methods you can see the distinction between property keys (strings and symbols), property names (only strings) and property symbols (only symbols) that we discussed previously.

Enumerability is an attribute of properties. By default, properties are enumerable, but there are ways to change that (shown in the next example and described in slightly more detail later).

For example:

  1. const enumerableSymbolKey = Symbol('enumerableSymbolKey');
  2. const nonEnumSymbolKey = Symbol('nonEnumSymbolKey');
  3. // We create the enumerable properties via an object literal
  4. const obj = {
  5. enumerableStringKey: 1,
  6. [enumerableSymbolKey]: 2,
  7. }
  8. // For the non-enumerable properties,
  9. // we need a more powerful tool:
  10. Object.defineProperties(obj, {
  11. nonEnumStringKey: {
  12. value: 3,
  13. enumerable: false,
  14. },
  15. [nonEnumSymbolKey]: {
  16. value: 4,
  17. enumerable: false,
  18. },
  19. });
  20. assert.deepEqual(
  21. Object.keys(obj),
  22. [ 'enumerableStringKey' ]);
  23. assert.deepEqual(
  24. Object.getOwnPropertyNames(obj),
  25. [ 'enumerableStringKey', 'nonEnumStringKey' ]);
  26. assert.deepEqual(
  27. Object.getOwnPropertySymbols(obj),
  28. [ enumerableSymbolKey, nonEnumSymbolKey ]);
  29. assert.deepEqual(
  30. Reflect.ownKeys(obj),
  31. [ 'enumerableStringKey',
  32. 'nonEnumStringKey',
  33. enumerableSymbolKey,
  34. nonEnumSymbolKey ]);

25.5.7. Listing property values via Object.values()

Object.values() lists the values of all enumerable properties of an object:

  1. const obj = {foo: 1, bar: 2};
  2. assert.deepEqual(
  3. Object.values(obj),
  4. [1, 2]);

25.5.8. Listing property entries via Object.entries()

Object.entries() lists key-value pairs of enumerable properties. Each pair is encoded as a two-element Array:

  1. const obj = {foo: 1, bar: 2};
  2. assert.deepEqual(
  3. Object.entries(obj),
  4. [
  5. ['foo', 1],
  6. ['bar', 2],
  7. ]);

25.5.9. Properties are listed deterministically

Own (non-inherited) properties of objects are always listed in the following order:

  • Properties with integer indices (e.g. Array indices)
  • In ascending numeric order
  • Remaining properties with string keys
  • In the order in which they were added
  • Properties with symbol keys
  • In the order in which they were added
    The following example demonstrates how property keys are sorted according to these rules:
  1. > Object.keys({b:0,a:0, 2:0,1:0})
  2. [ '1', '2', 'b', 'a' ]

(You can look up the details in the spec.)

25.5.10. Assembling objects via Object.fromEntries()

Given an iterable over [key,value] pairs, Object.fromEntries() creates an object:

  1. assert.deepEqual(
  2. Object.fromEntries([['foo',1], ['bar',2]]),
  3. {
  4. foo: 1,
  5. bar: 2,
  6. }
  7. );

It does the opposite of Object.entries().

Next, we’ll use Object.entries() and Object.fromEntries() to implement several tool functions from the library Underscore.

25.5.10.1. Example: pick(object, …keys)

pick() removes all properties from object whose keys are not among keys. The removal is non-destructive: pick() creates a modified copy and does not change the original. For example:

  1. const address = {
  2. street: 'Evergreen Terrace',
  3. number: '742',
  4. city: 'Springfield',
  5. state: 'NT',
  6. zip: '49007',
  7. };
  8. assert.deepEqual(
  9. pick(address, 'street', 'number'),
  10. {
  11. street: 'Evergreen Terrace',
  12. number: '742',
  13. }
  14. );

We can implement pick() as follows:

  1. function pick(object, ...keys) {
  2. const filteredEntries = Object.entries(object)
  3. .filter(([key, _value]) => keys.includes(key));
  4. return Object.fromEntries(filteredEntries);
  5. }
25.5.10.2. Example: invert(object)

invert() non-destructively swaps the keys and the values of an object:

  1. assert.deepEqual(
  2. invert({a: 1, b: 2, c: 3}),
  3. {1: 'a', 2: 'b', 3: 'c'}
  4. );

We can implement it like this:

  1. function invert(object) {
  2. const mappedEntries = Object.entries(object)
  3. .map(([key, value]) => [value, key]);
  4. return Object.fromEntries(mappedEntries);
  5. }
25.5.10.3. A simple implementation of Object.fromEntries()

Object.fromEntries() could be implemented as follows (I’ve omitted a few checks):

  1. function fromEntries(iterable) {
  2. const result = {};
  3. for (const [key, value] of iterable) {
  4. let coercedKey;
  5. if (typeof key === 'string' || typeof key === 'symbol') {
  6. coercedKey = key;
  7. } else {
  8. coercedKey = String(key);
  9. }
  10. Object.defineProperty(result, coercedKey, {
  11. value,
  12. writable: true,
  13. enumerable: true,
  14. configurable: true,
  15. });
  16. }
  17. return result;
  18. }

Notes:

25.6. Standard methods

Object.prototype defines several standard methods that can be overridden. Two important ones are:

  • .toString()
  • .valueOf()
    Roughly, .toString() configures how objects are converted to strings:
  1. > String({toString() { return 'Hello!' }})
  2. 'Hello!'
  3. > String({})
  4. '[object Object]'

And .valueOf() configures how objects are converted to numbers:

  1. > Number({valueOf() { return 123 }})
  2. 123
  3. > Number({})
  4. NaN

25.7. Advanced topics

The following subsections give a brief overviews of topics that are beyond the scope of this book.

25.7.1. Object.assign()

Object.assign() is a tool method:

  1. Object.assign(target, source_1, source_2, ···)

This expression (destructively) merges source_1 into target, then source_2 etc. At the end, it returns target. For example:

  1. const target = { foo: 1 };
  2. const result = Object.assign(
  3. target,
  4. {bar: 2},
  5. {baz: 3, bar: 4});
  6. assert.deepEqual(
  7. result, { foo: 1, bar: 4, baz: 3 });
  8. // target was changed!
  9. assert.deepEqual(target, result);

The use cases for Object.assign() are similar to those for spread properties. In a way, it spreads destructively.

For more information on Object.assign(), consult “Exploring ES6”.

25.7.2. Freezing objects

Object.freeze(obj) makes obj immutable: You can’t change or add properties or change the prototype of obj.

For example:

  1. const frozen = Object.freeze({ x: 2, y: 5 });
  2. assert.throws(
  3. () => { frozen.x = 7 },
  4. {
  5. name: 'TypeError',
  6. message: /^Cannot assign to read only property 'x'/,
  7. });

There is one caveat: Object.freeze(obj) freezes shallowly. That is, only the properties of obj are frozen, but not objects stored in properties.

For more information on Object.freeze(), consult “Speaking JavaScript”.

25.7.3. Property attributes and property descriptors

Just as objects are composed of properties, properties are composed of attributes. That is, you can configure more than just the value of a property – which is just one of several attributes. Other attributes include:

  • writable: Is it possible to change the value of the property?
  • enumerable: Is the property listed by Object.keys()?
    When you are using one of the operations for accessing property attributes, attributes are specified via property descriptors: objects where each property represents one attribute. For example, this is how you read the attributes of a property obj.foo:
  1. const obj = { foo: 123 };
  2. assert.deepEqual(
  3. Object.getOwnPropertyDescriptor(obj, 'foo'),
  4. {
  5. value: 123,
  6. writable: true,
  7. enumerable: true,
  8. configurable: true,
  9. });

And this is how you set the attributes of a property obj.bar:

  1. const obj = {
  2. foo: 1,
  3. bar: 2,
  4. };
  5. assert.deepEqual(Object.keys(obj), ['foo', 'bar']);
  6. // Hide property `bar` from Object.keys()
  7. Object.defineProperty(obj, 'bar', {
  8. enumerable: false,
  9. });
  10. assert.deepEqual(Object.keys(obj), ['foo']);

For more on property attributes and property descriptors, consult “Speaking JavaScript”.