JavaScript Objects

Object represents real-life entities, for example, a Bike is an object. The object has State, Behaviour, and Identity:

  • Identity: Name of Bike
  • State (Attributes): The data of object Bike i.e. Color, Model, Weight, etc.
  • Behavior (Methods): Behavior of object Bike like to Drive, Brake

Let us now see the representation, with Bike as an object:

JavaScript Objects

Everything is an object in JavaScript, but to create an object, you do not need to create a class. JavaScript does not have the concept of classes like Java.

Create an Object in JavaScript

To create an object, you need to separate the name and its value by the colon as shown below. The name:value pair is called property:

Note: We have used the const keyword to create an object since it is generally and widely preferred. The cost introduced in ES6.

Let us now see an example to create an object in JavaScript:

Output

JavaScript Objects Example

Create an object with Object() Constructor and new

The new keyword can also be used to create an object in JavaScript. Here, we will use the Object() constructor as well to create an object. Let us see an example:

Output

Create an object with JavaScript Object() Constructor and new

Access Object Properties

To access object properties in JavaScript, use the dot operator as well as square brackets. Let us see some examples:

Access Object Properties with the dot operator

The following is an example to access the student object properties using the dot operator in JavaScript:

Output

Access Object Properties with the dot operator

Access Object Properties with the square brackets

The following is an example to access the student object properties using the square brackets in JavaScript:

Output

Access Object Properties with the square brackets in JavaScript

JavaScript Events
JavaScript Numbers
Studyopedia Editorial Staff
Studyopedia Editorial Staff
[email protected]

We work to create programming tutorials for all.

No Comments

Post A Comment

Discover more from Studyopedia

Subscribe now to keep reading and get access to the full archive.

Continue reading