Object in JavaScript

Object in JavaScript

In JavaScript, an object is a collection of properties, and a property is an association between a key and a value. The object represents a non-primitive datatype in JavaScript. Object in Javascript is different from objects in other languages. It is much more powerful and important in JavaScript.

Creating an Object:

The object can be created in JavaScript mainly in 2 processes,

  1. Using Object Initializer: An object initializer is a comma-delimited list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ({}). Example:

     const person = {
       name: 'John',
       age: 30,
       greet: function() {
         console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
       }
     }
    

    In this example, name and age are key to the Object person; 'Jhon' and 24 are the values of their respective keys and greet is a method. We can access any properties of the object using dot notation (e.g., person.name) and we can call the object's methods using the same notation followed by parentheses (e.g., person.greet()).

  2. Using Object.create() method: This method allows us to create an object with a specific prototype and optionally define its properties. For example:

     const person = Object.create({}, {
       name: {
         value: 'John',
         writable: true,
         enumerable: true,
         configurable: true
       },
       age: {
         value: 30,
         writable: true,
         enumerable: true,
         configurable: true
       }
     });
     console.log(person); // { name: 'John', age: 30 }
    
  3. Using Object Constructor: The object constructor turns the input into an object. Let's see how it works:

     const person = new Object;
     person.name = "John";
     person.age = 24;
     person.state = "WB";
     console.log(person) //{ name: 'John', age: 24, state: 'WB' }
    
  4. Using Class: In ES6, we can even create Objects using class keyword. To create objects in this method, we need to define the class first, then using the new operator we can create a new object. Let's see an example of this:

     class Person {
       constructor(name, age) {
         this.name = name;
         this.age = age
       }
     }
     const person = new Person('Jhon', 30);
     console.log(person); //Person { name: 'Jhon', age: 30 }
    

Ok, ok… enough of creating objects, now we will see how to use them.

Modifying an Object:

Objects in JavaScript are mutable, which means we can modify an object after declaring it. To modify a property from an object, we have to mention the property using dot notation and simply assign the new value to it. Example:

const person = {
  name: 'John',
  age: 30,
}
person.age = 33;
console.log(person.age) //33

Deleting a property from an Object:

We can delete any property from an object using the delete operator. See the demo code:

const person = {
  name: "John",
  gender: "Male",
  age: 30,
};
delete person.age;
console.log(person); //{ name: 'John', gender: 'Male' }

Limiting the power of modifying an object:

As we saw in the previous point, modifying an object in JavaScript is very easy, but we can also restrict an Object for further modification, and we can do that also in different levels of strictness.

  • Seal Method: Using this method, we can seal an object, which means further addition or removal of properties in that object will not be allowed. (NOTE: Though we can't add or remove new properties to that object, we can still edit the existing properties of that object) We can also check if an object is sealed or not using the isSealed() method. Let's see an example of this method:

      const person = {
        name: "John",
        age: 30,
      };
      Object.seal(person);
      person.gender = "Male";
      person.age = 35;
      console.log(person); //{ name: 'John', age: 35 }
      console.log(Object.isSealed(person)) //true
    
  • Freeze Method: Using this method, we can completely freeze an object; which means the object will become completely immutable and making any kind of change in the properties will be restricted. We can also check if the object is frozen or not using the isFrozen() method. Example:

      const person = {
        name: "John",
        age: 30,
      };
      Object.freeze(person);
      person.gender = "Male";
      person.age = 35;
      console.log(person); //{ name: 'John', age: 30 }
      console.log(Object.isFrozen(person)) //true
    

Other than these, there are some built-in methods also present in the Object in JavaScript.

Some frequently used built-in methods are:

  • toString(): This method represents the object as a string. It is often used to convert the object into a string. Example:

      const person = {
        name: 'John',
        age: 30,
      }
      console.log(person.toString()) //'[object Object]'
    
  • hasOwnProperty(prop): This method is used to check if an object contains a given method in it or not. It returns a boolean value based upon the fact that the object contains the given property or not. Example:

      const person = {
         name: 'John',
         age: 30,
       } 
      console.log(person.hasOwnProperty("name")) //true
      console.log(person.hasOwnProperty("gender")) //false
    
  • Object.keys() & Object.values(): These methods separately return the keys and values of the object. See the code example:

      const person = {
        name: "John",
        gender: "Male",
        age: 30,
      };
      console.log(Object.keys(person)); //[ 'name', 'gender', 'age' ]
      console.log(Object.values(person)); //[ 'John', 'Male', 30 ]
    

These are the most frequently used methods and operations of Object in JavaScript. Yes, there is so much more we can do with objects in JavaScript, honestly speaking, it is the most powerful datatype in JavaScript. But to discuss all of them is not possible in a single article. If you want to know specifically about some method of Object in JavaScript, you can ask me in comment, and I'll surely try to write an article on that. Thanks for reading.