JavaScript/Objects

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
The JavaScript syntax supports different ways to create objects.

'Literal notation' using curly braces

Constructor The  constructor creates a new object.

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

Read a property
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.

What if you don't know the keys? To get a list of all existing keys, use the method. 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  loop selects the keys and loops over all properties.

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

Add or modify a property
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.

In the above example, the variable 'person' is created with the keyword. 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
The  operator removes the complete property from an object - the key as well as the value. This is different from the case where someone stores  or   in the value.

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

Merge objects
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.

Functions/methods as part of an object
The value part of a property may contain the body of a function; see here. In this case, the function is called a method.

Exercises

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

Programación en JavaScript/ClasesJS JavaScript/Oggetti Javascript/Objetos