Skip to content

JavaScript Object

  • by

In JavaScript, an object is a data structure that stores key-value pairs. It can hold various types of data, including strings, numbers, booleans, arrays, and even other objects.

Objects are created using object literals or the object constructor function, and properties can be accessed using dot notation or bracket notation.

The syntax for creating an object using an object literal is as follows:

const myObject = {
  // Properties and methods go here
  property1: value1,
  property2: value2,
  method: function() {
    // Method code goes here
  }
};

To create an object using a constructor function, the syntax is:

function MyObject(arg1, arg2) {
  // Properties and methods go here
  this.property1 = arg1;
  this.property2 = arg2;
  this.method = function() {
    // Method code goes here
  }
}

const myObject = new MyObject(value1, value2);

Objects are commonly used in JavaScript to represent real-world objects and are frequently used in combination with functions to create more complex code structures.

JavaScript Object example

Simple example code creating an object literal. Object literals are a concise way to create objects using curly braces {}. They allow you to define properties and methods directly on the object, like this:

<!DOCTYPE html>
<html>
<body>
    <script>
       const person = {
        name: 'John',
        age: 30,
        hobbies: ['reading', 'traveling'],
        address: {
            street: '123 Main St',
            city: 'Anytown',
            state: 'CA'
        }
    };

    // access the properties of an object 
    console.log(person.name); 
    console.log(person['age']); 
    console.log(person.hobbies[0]); 
    console.log(person.address.city);

    // update properties of an object
    person.email = '[email protected]';
    person.age = 31;

    console.log(person)


    </script>
</body>
</html>

Output:

JavaScript Object

Constructor functions are used to create objects with properties and methods. They are like classes in other programming languages.

function Person(name, age, hobbies) {
  this.name = name;
  this.age = age;
  this.hobbies = hobbies;
  this.sayHello = function() {
    console.log(`Hello, my name is ${this.name}.`);
  }
}

const person = new Person('John', 30, ['reading', 'traveling']);

Do comment if you have any doubts or suggestions on this JS Object topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *