JavaScript Object and its method

JavaScript Object and its method

In JavaScript, an object is a collection of key-value pairs where each key is a string (or symbol) and each value can be any data type, including other objects. Objects are commonly used to represent complex data structures and to organize related data.

To create an object in JavaScript, you can use either object literal notation or the Object constructor function:

// Object literal notation
const person = { name: 'John', age: 30 };

// Object constructor function
const person = new Object({ name: 'John', age: 30 });

Once you have created an object, you can access its properties using dot notation or bracket notation:

console.log(person.name); // Output: 'John'
console.log(person['age']); // Output: 30

JavaScript also provides several built-in methods that can be used to manipulate and transform objects. Some of the most commonly used object methods include:

  • Object.keys() : returns an array of the keys in an object.
  • Object.values() : returns an array of the values in an object.
  • Object.entries() : returns an array of key-value pairs in an object.
  • Object.assign() : copies the properties from one or more source objects to a target object.
  • Object.freeze() : prevents the properties of an object from being modified.
  • Object.seal() : prevents new properties from being added to an object and prevents existing properties from being deleted.

Here's an example of using the Object.keys() method:

const person = { name: 'John', age: 30 };
const keys = Object.keys(person);

console.log(keys); // Output: ['name', 'age']

In this example, the Object.keys() method is used to return an array of the keys in the person object. The resulting keys array contains the values 'name' and 'age'.

Overall, JavaScript objects are a powerful and flexible data type that allows developers to represent and manipulate complex data structures.