Objects in JavaScript

ยท

4 min read

An object is an unordered collection of properties, with a name (or key) and a value. In JavaScript, they are the most fundamental data type used to store and retrieve values, which can be primitive values or other objects. The most common operations to do with objects are to create them, set, query, delete, test, and enumerate their properties, however, many JavaScript's built-in objects have properties that are read-only, non-enumerable, or non-configurable.

Creating Objects

To create objects in JavaScript, we can use the object literal syntax, the new keyword, and the Object.create() function.

An object literal syntax is the easiest way to create an object in JavaScript, and it is a comma-separated list of colon-separated name: value pairs, enclosed within curly braces. An object literal is an expression that creates and initializes a new and distinct object each time it is evaluated. The value of each property is evaluated each time the literal is evaluated. This means that a single object literal can create new objects if it appears in the body of a loop or in a repeatedly called function.

Example:

let house = {
      color: "white",
      garden: true,
      "family members": 4,
      place() {
          console.log("The house is situated in San Francisco");
  }
};

The new operator creates and initializes a new object, and it must be followed by a function invocation, called a constructor, that starts with a capital letter, and should be called only with the new keyword. Moreover, the constructor function allows you to create multiple similar objects.

The following example defines a constructor function called Person:

function Person(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
}

To create a new instance of Person, use the new operator:

let person = new Person('John','Doe');

Objects can also be created using the Object.create() method that allows you to choose the prototype object for the object you want to create. You can pass null to create a new object that does not have a property, however, the newly created object will not inherit anything, not even a basic method like toString().

let x = Object.create(null);

You can also create an empty object using:

let y = Object.create(Object.prototype) /* y is like {} or new Object();*/

More understandable example:

const car = {
  color: 'red', 
  displayColor() {  
    console.log(`This car is ${this.color}`);
  }
};

const car2= Object.create(car);
car2.color = "blue"; // inherited properties can be overwritten

Querying and Setting Properties

To obtain the value of a property, use the dot (.) or square bracket ([]) operators. If using the dot operator, the righthand side must be a simple identifier that names the property.

let carColor = car.color;

If using square brackets, the value within the brackets must be an expression that evaluates to a string or a value that can be converted to a string or to a Symbol that contains the desired property name.

let familyMembers = house["family members"];

Deleting properties

The delete operator does not operate on the value of the property but on the property itself, so remove an entire property from an Object. The delete operator only deletes own properties, not inherited ones, and evaluates to true if the delete succeeded or if the delete had no effect. Moreover, delete does not remove properties that have a configurable attribute of false.

delete car.color;

delete house["family members"];

Testing Properties

You can test a properties using the in operator, the hasOwnProperty() and propertyIsEnumerable() methods.

The in operator returns true if the object has an own property or an inherited property by that name.

let myName = { name: "Andrea" };

"name" in myName /* true: myName has an own property "name" */

The hasOwnProperty() tests whether the object has an own property with the given name, but returns false for inherited property.

let animal = { type: "wolf" };

animal.hasOwnProperty("type");  /* true: animal has an own property type */
animal.hasOwnProperty("toString");  /* false: toString is an inherited property */

The propertyIsEnumerable() returns true only if the named property is an own property and its enumerable attribute is true.

let number = { x: 1 };

number.propertyIsEnumerable("x");  /* true: number has an own enumerable property x */

Extending Objects

A common operation in JavaScript programs is needing to copy the properties of one object to another object. In ES6, we can achieve this with Object.assign().

Object.assign() expects two or more objects as its arguments. It modifies and returns the first argument, which is the target object, but does not alter the second, or any subsequent arguments, which are the source objects. For each source object, it copies the enumerable own properties of that object into the target object.

const target = { a: 1, b: 2 };
const source = { b: 3, c: 7 };

const newTarget = Object.assign(target, source);

Conclusion

Objects in JavaScript penetrate almost every aspect of the language, so it is important to understand them in detail. I hope that this article helps you to improve your knowledge of JavaScript objects. However, if there are incorrect statements or errors of any type or you want to talk about any JavaScript features, I would like to get in touch to discuss them.

ย