JavaScript Object {} and its method

ยท

2 min read

One of the most important features of JavaScript is the ability to create and manipulate objects. Objects are a collection of related data and functionality, which can be accessed and manipulated through their properties and methods. In this blog post, we will discuss JavaScript objects and their methods in detail, with code examples.

What is a JavaScript Object?

In JavaScript, an object is a collection of properties, which can be used to represent real-world entities or concepts. Objects can be created using object literals, constructor functions, or the object.create() method. Each property in an object consists of a key-value pair, where the key is a string or symbol, and the value can be any valid JavaScript value.

Object Literals:

The simplest way to create an object in JavaScript is to use an object literal. An object literal is a comma-separated list of key-value pairs enclosed in curly braces {}. Here's an example of an object literal:

const person = {
  name: 'John',
  age: 30,
  address: {
    city: 'New York',
    state: 'NY',
    country: 'USA'
  },
  hobbies: ['reading', 'running', 'traveling'],
  greet: function() {
    console.log(`Hi, my name is ${this.name}.`);
  }
};

In this example, we have created an object called person, which has four properties: name, age, address, and hobbies. The address property is an object itself, which has three sub-properties: city, state, and country. The hobbies property is an array of strings. Finally, the greet property is a function that logs a message to the console.

Constructor Functions:

Another way to create an object in JavaScript is to use a constructor function. A constructor function is a special function that is used to create objects of a specific type. Here's an example of a constructor function:

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

const person = new Person('John', 30, {city: 'New York', state: 'NY', country: 'USA'}, ['reading', 'running', 'traveling']);

In this example, we have created a constructor function called Person, which takes four parameters: name, age, address, and hobbies. Inside the constructor function, we are setting the values of the object's properties using the this keyword. Finally, we are creating a new object called person using the new keyword and passing in the necessary parameters.

ย