A Platform To Learn To Code

JAVASCRIPT OBJECTS



Javascript object is a Data type that is a collection of properties and methods.

The properties and values are stored in a key-value pair.

Javascript is an object-based language, everything in javascript is an object or can be made an object using a new keyword. Example

  • Numbers can be made object using new keyword
  • Boolean can be made object using new keyword
  • Strings can be made object using new keyword
  • Array is an object
  • Function is an object
  • Date is an object
  • Regex (Regular Expression) is an object
  • Maths is an object
  • Objects are always objects


How to create object in javascript

In javascript, objects can be created using many different methods.

  1. Creating object using object literals
  2. Creating object with constructor
  3. Creating object With object.create() method
  4. Creating object using javascript class


1. Creating object using object literals

Object is created using object literal by assigning curly braces to the variable name.

Here is how to create an empty object.

Property is added to the object in key-value pairs, value could be any data type.Now, here is how to add a key : value pair in the object.

Here, the object person has three properties: firstname, lastname and age.


2. Creating object with constructor

Creating a javascript object using the constructor method is most easy and convenient to create multiple objects.

Constructor is just a javascript function, which constructs objects when called with new keyword.

Here is how to create an object using a constructor function.

constructor method

Run the code

Output:

javascript-constructor-object

3. Creating object With object.create() method

The Object.create() method is used to create object using older objects as a prototype. Using this method all the properties that are created referring to older objects, has to be given value in new object

Object.create() method

Run the code

Output:

javascript object using object create method

4. Creating object using javascript class

Objects in javascript can also be created using javascript ES6 classes.

Class method

Run the code

Output:

javascript object using class

Javascript object Method

object method is a function that operates on an object.

object method is part of the object in the form of a key value pair.

To access object method write method name followed by object name connected with dot. Here is an example:

Check Working example.

object method

Run the code

this keyword in javascript object

this keyword indicates the parent object of the function. this referes to the object which is holding the function.

In the above example this indicates the money object. In remaining function this.earning = money.earning, this.spent = money.spent and so on.

BOX