JavaScript Objects


Javascript is the object-oriented programming language of the language. Objects like C++, Java are also created in Javascript. JavaScript object has some methods and some properties.

JavaScript object is an individual entity that can hold various values. it is called properties or methods.

Objects in JavaScript are created in three ways.

  • Object literal
  • New keyword
  • Object Constructor

Object literal

Object Literal is enclosed in braces. Each property and value is separated by a colon (:) and each property and value pair is separated by a comma (,).

Syntax

var <object-name> = { key1: value1, key2: value2,... keyN: valueN};

Example

<script type="text/javascript">
 var person = {"first_name": "Clark", "last_name": "Mark", "age": "25"};
</script>

New keyword

The object is created with a new keyword. so you can see the following syntax or example for creating an object using the new keyword.

Syntax

var <object-name> = new Object();

Example

<script type="text/javascript">
 var person = new Object();
 person.first_name= "Clark";
 person.last_name= "Mark";
 person.age = 25;
</script>

Object Constructor

Object Constructor requires functions and their parameters. This keyword refers to the current object.

Here this parameter will be assigned the current object value of each parameter. Through Object Constructor, more than one object is created in a short form.

Example

<script type="text/javascript">
function person (first_name, last_name, age){
  this.first_name= first_name;
  this.last_name= last_name;
  this.age= age;
}

var person1 = new person("Clark","Mark",25);
</script>