JavaScript Objects

JavaScript Objects



1. The object literal is the simplest way to create objects

The simplest way to create an object is to use the object literal. We define a set of properties inside curly braces {} separated by commas. Below is an example.
const game = {
name: 'Fornite',
developer: 'Epic Games'
};
 
The previous object has two properties. The first property has the key name and the value Fornite.

2. Objects are dynamic collections of properties

Indeed object is a dynamic collection of props.

Once an object is created we can add, edit or delete properties from it. Below is an example of adding and deleting the year property to/from the previous game object.

game.year = 2017;
delete game.year;

3. Properties can be accessed using the dot and the bracket notations

Properties can be accessed using the dot notation when the key is a valid identifier.

console.log(game.name)

When the key is not a valid identifier we need to use the bracket notation.

console.log(game["name"])

4. Keys are converted to strings

Keys are string only. When non-string values are used as keys they are converted to strings. Look what happens when I try to use another object as a key.

const developerKey = {
toString(){
return 'developer'
}
}
console.log(game[developerKey]);
//Epic Games

When the developerKey is used as a key it is first converted to a string using the toString method, then the result 'developer' string key is used to retrieve the value. The previous code gives the same result as game['developer'].

5. Objects inherit from other objects

In JavaScript, objects inherit from other objects. Objects have a hidden property called __proto__ pointing to their prototype. All objects inherit from the global Object.prototype.

game.__proto__ === Object.prototype;
//true

The game object has properties like toString or toLocaleString even if we haven’t defined such methods. They are inherited from the Object.prototype object.

console.log(game.toString);
//ƒ toString() { [native code] }
console.log(game.toLocaleString);
//ƒ toLocaleString() { [native code] }
The Object.create() takes a prototype object and creates a new object pointing to it.

Comments