Show List

JavaScript Objects

JavaScript objects are collections of properties (keys) and values. They are similar to dictionaries in other programming languages. Objects are dynamic, meaning you can add, modify, or remove properties at any time. They are also unordered, meaning that the order in which the properties are defined does not matter. Properties can be values of any data type, including other objects. JavaScript objects are used to model real-world objects and to organize code. They are a fundamental part of the language and are used extensively in web development and other applications.

JavaScript objects can be created in any of the following ways:

Define and create object in one statement
      let person = {
        firstName: "John",
        lastName: "Miller",
        age: 35,
      };

Using new keyword
      let person = new Object();
      person.firstName = "John";
      person.lastName = "Miller";
      person.age = 35;

Using class constructor
      class Person {
        constructor(firstName, lastName, age) {
          this.firstName = firstName;
          this.lastName = lastName;
          this.age = age;
        }
      }

      let person = new Person("John", "Miller", "35");

Using Object.create()
This is used to create new object using an existing object as prototype. Object.create method takes two parameters. The first parameter is mandatory prototype object. The second parameter is optional object which contains the properties to be added to the new object being created.
      class LastNames {
        constructor(lastName) {
          this.lastName = lastName;
        }
      }

      let millers = new LastNames("Miller");  
      let personA = Object.create(millers,  { firstName : {value:'John'} , age : {value:'35'} });

    Leave a Comment


  • captcha text