JavaScript Object and it's method

In JavaScript, an object is a collection of key-value pairs, where each key represents a property and its associated value. Objects provide a way to store and organize related data and functionality. Here's an example of creating an object:

// Creating an object
const person = {
  name: 'John',
  age: 30,
  profession: 'Developer'
};

In the example above, we create an object called person with properties like name, age, and profession. Each property has a corresponding value.

JavaScript objects also have built-in methods that can be used to perform various operations. Here are a few commonly used methods:

  1. Object.keys(): This method returns an array of strings representing all the enumerable properties of an object.

     const keys = Object.keys(person);
     console.log(keys); // Output: ['name', 'age', 'profession']
    
  2. Object.values(): This method returns an array of all the values of the enumerable properties of an object.

     const values = Object.values(person);
     console.log(values); // Output: ['John', 30, 'Developer']
    
  3. Object.entries(): This method returns an array of arrays, where each subarray contains a key-value pair of an object's enumerable properties.

     const entries = Object.entries(person);
     console.log(entries); // Output: [['name', 'John'], ['age', 30], ['profession', 'Developer']]
    
  4. Object.assign(): This method is used to copy the values of all enumerable properties from one or more source objects to a target object.

     const person2 = {
       location: 'USA'
     };
    
     const mergedPerson = Object.assign({}, person, person2);
     console.log(mergedPerson); // Output: { name: 'John', age: 30, profession: 'Developer', location: 'USA' }
    
  5. Object.hasOwnProperty(): This method checks if an object has a specific property and returns a boolean indicating whether the object has the property directly (not inherited).

     console.log(person.hasOwnProperty('age')); // Output: true
     console.log(person.hasOwnProperty('gender')); // Output: false
    

These are just a few examples of JavaScript object methods. JavaScript objects have many other useful methods like Object.freeze(), Object.seal(), and Object.getPrototypeOf() that provide additional functionality for working with objects.