In JavaScript, an Object is a collection of properties; properties are key-value pairs. The keys are Strings or Symbols. Values can be of any data type - including functions (in this case, they are called methods).

Objects look like associative arrays implemented as hashtables. But in practice, JavaScript engines might have implemented them in other ways to achieve optimal performance.

Please consider that JavaScript objects are not identical to JSON. JSON is a format for a textual representation ('serialization' / 'de-serialization') of objects, which can also be done in other languages or in a pure text editor.

Create an object edit

The JavaScript syntax supports different ways to create objects.

'Literal notation' using curly braces { }

"use strict";

// an empty object (no properties)
const obj_0 = {};
alert(JSON.stringify(obj_0));

// 'obj_1' contains a set of 3 properties. The value of key 'c' is
//         a second object with an empty set of properties.
const obj_1 = { a: "Any string", b: 42, c: {} };
alert(JSON.stringify(obj_1));

// using variables
const a = "Any string";
const b = 42;
const c = {};
const obj_2 = { a: a, b: b, c: c };
alert(JSON.stringify(obj_2));

// shorthand usage of variables
const obj_3 = { a, b, c };
alert(JSON.stringify(obj_3));

Constructor
The new Object() constructor creates a new object.

"use strict";
const obj_4 = new Object({ a: 5, b: 42 });
alert(JSON.stringify(obj_4));

Object.create()
The Object.create() method creates a new object from an existing object.

"use strict";
const obj_5 = Object.create({ a: 5, b: 42 });
alert(JSON.stringify(obj_5));  // ???
alert(JSON.stringify(obj_5.a));
console.log (obj_5);

Read a property edit

Each property consists of a key-value pair. To read a property's values, you can use its key in one of two syntactical ways, dot notation or bracket notation.

"use strict";
const person = {firstName: "Albert", lastName: "Einstein" };

// dot notation
alert(person.firstName);   // no " " or ' '

// bracket notation
alert(person["firstName"]); // must use a string

// bracket notation using a variable
const fn = "firstName";
alert(person[fn]);

What if you don't know the keys? To get a list of all existing keys, use the method Object.keys(). It returns an array whose elements are strings. Those strings may be used in a loop to access the values. Because you need such loops in many cases, JavaScript offers a special language element for that situation. The for .. in loop selects the keys and loops over all properties.

"use strict";
const person = {firstName: "Albert", lastName: "Einstein" };
alert(Object.keys(person));   // firstName, lastName

// The for .. in loop selects all existing keys and loops over the properties
for (const k in person) {
  alert('The key is: ' + k + '. The value is: ' + person[k]);
}

Analog to the Object.keys() method there are the two methods Object.values() and Object.entries() to get the values respectively the properties (key and value). In the latter case, you get an array of arrays (with two elements each).

"use strict";
const person = {firstName: "Albert", lastName: "Einstein" };
alert(Object.values(person));   // Albert, Einstein

// for .. of loops differ from for .. in loops in syntax AND semantic; see chapter 'Loops'
for (const [k, v] of Object.entries(person)) {
  alert('The key is: ' + k + '. The value is: ' + v);
}

Add or modify a property edit

You can use the dot notation as well as the bracket notation to add or modify properties. There is no difference in the syntax between the above read operations and the write operations.

"use strict";
const person = {firstName: "Albert", lastName: "Einstein" };

// add properties
person.bornIn = "Ulm";
person["profession"] = "Physicist";
alert(JSON.stringify(person));

// modify properties
person.bornIn = "Germany";
person["profession"] = "Theoretical Physics";
alert(JSON.stringify(person));

In the above example, the variable 'person' is created with the keyword const. So it's not possible to assign a new value to it, but it's possible to manipulate its properties. When manipulating properties, the original object keeps unchanged.

Delete a property edit

The delete operator removes the complete property from an object - the key as well as the value. This is different from the case where someone stores null or undefined in the value.

Again, you can use the dot notation as well as the bracket notation.

"use strict";
const person = {firstName: "Albert", lastName: "Einstein", bornIn: "Ulm", profession: "Physicist" };

delete person.bornIn;
delete person["profession"];
alert(JSON.stringify(person));

Merge objects edit

JavaScript offers a 'spread syntax' (3 dots). It expands an Object to its properties (key-value pairs) or an array to its elements. This can be helpful when you want to merge multiple objects into a single one.

"use strict";
const person = {firstName: "Albert", lastName: "Einstein" };
const address = {city: "Ulm" };

// expand the two objects (and merge them)
const newPerson = {...person, ...address};
alert(JSON.stringify(newPerson));
// The result is an object with 3 properties. All values are strings.
// {firstName: "Albert", lastName: "Einstein",city: "Ulm"}

// which is different from the version without the 'spread syntax':
const newPerson1 = {person, address};
alert(JSON.stringify(newPerson1));
// The result is an object with 2 properties. Both values are objects.
// {person: {firstName: "Albert", lastName: "Einstein"}, address: {city: "Ulm"}}

Functions/methods as part of an object edit

The value part of a property may contain the body of a function; see here. In this case, the function is called a method.

"use strict";

// only definitions here, no execution!
const city = {
  showName: function (cityName) {
              if (typeof cityName === "undefined") {
                alert("Sorry, I don't know my name.");
              } else {
                alert("The name of the city is: " + cityName);
              }
            },

  // this works too!
  showPopulation(count) {
    alert(count + " Inhabitants");
  },
};

// JSON's 'stringify()' doesn't support the serialization of methods. Use 'console.log()' instead.
console.log(city);

// executions
city.showName();
city.showName("Nairobi");
city.showPopulation(4500000);

Exercises edit

... are available on another page (click here).