An object is a collection of properties, where each property is an association between a name(or key) and a value.In JavaScript, an object is a standalone entity with properties and a specific type. For example,consider an animal. An animal has properties such as color, structure, and weight. Similarly, JavaScript objects have properties that define their characteristics.

We can create an object initializer. An object initializer is a comma-separated list of one or more property names and their corresponding values, enclosed in curly braces{}.

Creating an Object

An object in JavaScript can be created with four properties using different methods.

First Method: Using object Initializer

An object initializer allows defining properties within curly braces {}. It can span multiple lines, making it easy to read and manage.

Second Method: creating an Empty object and Adding Properties

We can create an empty object and add properties dynamically.

Third Method: Using new Keyword

The new object () syntax creates an object instance.

Accessing Object

We can access an object in two methods

  • Dot Notation
  • Bracket Notation

Dot Notation

Used when the property name is known and follows standard variable naming rules.

object.property

Bracket Notation

Used when the property name is dynamic, contains special characters, or is stored as a variable.

Changing Object Property

We can change object property but can’t able to change object once initialize.

In below code, The model of object is changed to Creta.

Delete Object Property

In deleting an object property, by using “delete” keyword property of object is deleted.

Methods of Object

Object.values()

By using Object.values() we can take only the values of the object.

Object.keys()

By using Object.keys() method take only the keys of the object.

Object.entries()

Object.freeze()

Once an object is frozen the property we cannot able to change or delete its property of object.

In this snippet object is frozen and the color of object is changed to white after freeze but color of object is unchanged. Second same color of the object is deleted but it is not delete.

Object.seal()

Once an object is sealed, we can modify existing properties but cannot add or deleted properties.

In this snippet first object is sealed and then change the color of the vehicle it is changed but when deleting the color it is not deleted.

Leave a Reply