Home Web DevelopmentFront-End Mastering Object Methods in JavaScript

Mastering Object Methods in JavaScript

by aouidane.med.amine
56,766 views 5 min read

This tutorial is designed to provide you with a thorough understanding of object methods in JavaScript and how to use them effectively in your code.

We will start by introducing objects and object methods, and explore how to access object properties using dot notation and bracket notation.

We will cover then advanced topics like freezing and sealing objects, combining objects with Object.assign(), and checking object properties with Object.hasOwnProperty().

We’ll also explore more advanced object methods like Proxies and Symbols and provide best practices and tips for using object methods in your code.

Table of Contents

What is an Object in javascript ?

In JavaScript, an object is a collection of properties, where each property has a name and a value.

Properties can be raw values, such as strings or numbers, or they can be functions, called object methods.

For example, here’s an object that represents a person:

				
					let person = {
  name: 'Aouidane',
  age: 33,
  sayHello: function() {
    console.log('Hello!');
  }
};

				
			

This object has three properties: name, age, and sayHello.

The sayHello property is a function that can be called using dot notation like this: person.sayHello().

Accessing Object Properties

In JavaScript, there are two ways to access object properties: dot notation and bracket notation.

 

dot notation 

Dot notation is used to access object properties by specifying the object name followed by a dot (.) and the property name

For example:

				
					let person = {
  name: 'Aouidane',
  age: 33
};

console.log(person.name); // Output: Aouidane

				
			

Here, we’re using dot notation to access the name property of the person object.

Bracket notation

We can use Bracket notation to access object properties by specifying the object name followed by square brackets [] and the property name as a string

For example:

				
					let person = {
  name: 'Aouidane',
  age: 30
};

console.log(person['name']); // Output: Aouidane

				
			

In general, dot notation is preferred for accessing properties that have valid identifier names, while bracket notation is useful for accessing properties with dynamic or computed names.

For example:

				
					let propertyName = 'Aouidane';

console.log(person[propertyName]); // Output: Aouidane

				
			

Using Object Methods for Iteration and Enumeration

In JavaScript, objects have several methods that allow us to perform multiple operations on them.

These methods include Object.keys(), Object.values(), Object.entries(), and for...in loops.

Object.keys()

Object.keys() is a method that returns an array of the object’s property names.

For example:

				
					let person = {
  name: 'Aouidane',
  age: 33
};

let keys = Object.keys(person);

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

				
			

Object.values()

Object.values() is a method that returns an array of the object’s property values.

For example:

				
					let person = {
  name: 'Aouidane',
  age: 33
};

let values = Object.values(person);

console.log(values); // Output: ['Aouidane', 33]

				
			

Object.entries()

Object.entries() is a method that returns an array of arrays, where each inner array contains a property name and its corresponding value.

For example:

				
					let person = {
  name: 'Aouidane',
  age: 33
};

let entries = Object.entries(person);

console.log(entries); // Output: [['name', 'Aouidane'], ['age', 33]]

				
			

for…in

for...in loops allow us to loop through all the properties of an object and perform some operation on each one.

For example:

				
					let person = {
  name: 'Aouidane',
  age: 33
};

for (let property in person) {
  console.log(`${property}: ${person[property]}`);
}
// Output:
// name: Aouidane
// age: 33

				
			

Modifying Objects with Object Methods

In JavaScript, we can modify objects using multiple methods. These methods allow us to add new properties, delete existing ones, and update the values of existing properties.

Add a new property

To add a new property to an object, we can simply assign a value to a new property name.

For example:

				
					let person = {
  name: 'Aouidane',
  age: 33
};

person.city = 'Paris';

console.log(person);
// Output: { name: 'Aouidane', age: 33, city: 'Paris' }

				
			

Delete property

To delete an existing property from an object, we can use the delete operator followed by the property name.

For example:

				
					let person = {
  name: 'Aouidane',
  age: 33,
  city: 'Paris'
};

delete person.city;

console.log(person);
// Output: { name: 'Aouidane', age: 33 }

				
			

Update property

To update the value of an existing property, we can simply assign a new value to the property name.

For example:

				
					let person = {
  name: 'Aouidane',
  age: 33
};

person.age = 34;

console.log(person);
// Output: { name: 'Aouidane', age: 34 }

				
			

Freezing and Sealing Objects

In JavaScript, we can make objects immutable using the Object.freeze() and Object.seal() methods.

Object.freeze()

Object.freeze() is a method that prevents any modifications to an object’s properties. Once an object is frozen, its properties cannot be added, deleted, or updated.

For example:

				
					let person = {
  name: 'Aouidane',
  age: 33
};

Object.freeze(person);

person.age = 34;

console.log(person); // Output: { name: 'Aouidane', age: 33 }

				
			

Object.seal()

Object.seal() is a method that prevents any additions or deletions of an object’s properties. However, the values of existing properties can still be updated.

For example:

				
					let person = {
  name: 'Aouidane',
  age: 33
};

Object.seal(person);

person.city = 'Aouidane';
delete person.age;
person.age = 34;

console.log(person);
// Output: { name: 'Aouidane', age: 34 }

				
			

Combining Objects with Object.assign()

In JavaScript, we can combine objects using the Object.assign() method.

This method allows us to copy the values of all properties from one or more source objects to a target object.

For example:

				
					let person = {
  name: 'Aouidane',
  age: 33
};

let job = {
  title: 'Software Engineer',
  company: 'Harmonie.'
};

let newPerson = Object.assign({}, person, job);

console.log(newPerson); 
// Output: { name: 'Aouidane', age: 33,
// title: 'Software Engineer', company: 'Harmonie' }

				
			

Here, we are using Object.assign() to combine the person and job objects into a new object called newPerson.

Advanced Object Methods

In JavaScript, there are two advanced object methods that allow us to extend and customize object behavior: Proxy and Symbol.

Proxy Method

Proxy allows us to intercept and customize operations on objects, such as property access, assignment, deletion, and more.

Example:

				
					let person = {
  name: 'Aouidane',
  age: 33
};

let personProxy = new Proxy(person, {
  get(target, prop) {
    console.log(`Getting property "${prop}"`);
    return target[prop];
  },
  set(target, prop, value) {
    console.log(`Setting property "${prop}" to value "${value}"`);
    target[prop] = value;
    return true;
  }
});

console.log(personProxy.name); 
// Output: Getting property "name"; Aouidane

personProxy.age = 34; 
// Output: Setting property "age" to value "34"

console.log(person.age); 
// Output: 34

				
			

Symbol Method

Symbol allows us to create unique value that can be used as property keys in objects.

Example:

				
					const firstName = Symbol('first-name');
const lastName = Symbol('last-name');

let person = {
  [firstName]: 'Aouidane',
  [lastName]: 'Amine'
};

console.log(person[firstName]); // Output: Aouidane
console.log(person[lastName]); // Output: Amine
console.log(Object.keys(person)); // Output: []

				
			

As you see, Object.keys() doesn’t include the symbol properties, since they are not enumerable.

Generally, Symbol are used when the property name is not a valid identifier (when it contains spaces or special characters).

References and Links

You may also like