How To Use Object Methods in JavaScript?

You are currently viewing How To Use Object Methods in JavaScript?

Introduction:

JavaScript, as a versatile and powerful language, offers a myriad of ways to manipulate and interact with objects. Object methods play a pivotal role in this process, empowering developers to perform various operations on objects efficiently. In this comprehensive guide, we will delve deep into the world of object methods in JavaScript, exploring their syntax, usage, and best practices.

Understanding Objects in JavaScript:

Before we dive into object methods, let’s refresh our understanding of objects in JavaScript. Objects are complex data structures consisting of key-value pairs, where each key is a string (or symbol) and each value can be of any data type, including other objects, arrays, functions, and primitive values.

// Example of an object
let person = {
    name: "John",
    age: 30,
    address: {
        city: "New York",
        country: "USA"
    },
    greet: function() {
        return `Hello, my name is ${this.name}.`;
    }
};

Object.keys():

Object.keys() Returns an array of a given object’s own enumerable property names.

const person = {
  name: 'John',
  age: 30,
  address: '123 Main St'
};
const keys = Object.keys(person);
console.log(keys); // Output: ["name", "age", "address"]

Object.values():

Object.values() Returns an array of a given object’s own enumerable property values.

const values = Object.values(person);
console.log(values); // Output: ["John", 30, "123 Main St"]

Object.entries():

Returns an array of a given object’s own enumerable string-keyed property [key, value] pairs.

const entries = Object.entries(person);
console.log(entries); 
// Output: [["name", "John"], ["age", 30], ["address", "123 Main St"]]

Object.assign():

Object.assign() Copies the values of all enumerable own properties from one or more source objects to a target object. It returns the target object.

const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };

const result = Object.assign(target, source);
console.log(result); // Output: { a: 1, b: 4, c: 5 }

Object.freeze()

Object.freeze() Freezes an object, preventing new properties from being added to it, existing properties from being removed, and changes to the enumerability, configurability, or writability of its properties.

const frozenPerson = Object.freeze(person);
// Attempt to add a new property
frozenPerson.newProperty = 'Value'; // This will not add a new property
console.log(frozenPerson.newProperty); // Output: undefined

Object.seal():

Object.seal() Seals an object, preventing new properties from being added to it and marking all existing properties as non-configurable.

const sealedPerson = Object.seal(person);
// Attempt to add a new property
sealedPerson.newProperty = 'Value'; // This will not add a new property
console.log(sealedPerson.newProperty); // Output: undefined

Object.preventExtensions()

Object.preventExtensions(). It prevents new properties from being added to an object, effectively preventing its extension. Here’s how it works:

const obj = { a: 1, b: 2 };

Object.preventExtensions(obj);

// Attempt to add a new property
obj.c = 3; // This property addition will be ignored in strict mode or throw a TypeError in sloppy mode

console.log(obj); // Output: { a: 1, b: 2 }

In this example, after calling Object.preventExtensions(obj), any attempt to add new properties (obj.c = 3) will fail silently in strict mode or throw a TypeError in non-strict mode, effectively preventing the object from being extended.

Object.getOwnPropertyNames():

Object.getOwnPropertyNames() Returns an array of all properties (enumerable or not) found directly upon a given object.

const propertyNames = Object.getOwnPropertyNames(person);
console.log(propertyNames); 
// Output: ["name", "age", "address"]

Object.hasOwnProperty():

Object.hasOwnProperty() Returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it).

console.log(person.hasOwnProperty('name')); // Output: true
console.log(person.hasOwnProperty('toString')); // Output: false

These are some of the commonly used Object methods in JavaScript, each serving a specific purpose in object manipulation and management.

If you need to review JavaScript objects you can read “Demystifying Objects in JavaScript: A Comprehensive Guide

Leave a Reply