JavaScript Object

Object in JavaScript

JavaScript Object:

JavaScript variables are containers for data values.So JavaScript Object are variables too, but they can contain many values.

Think of an object as a list of values that are written as name:value pairs, with the names and the values separated by colons.


Example:

   var person = {

 name: "John", age: 31, 

 favColor: "green", height: 183

};

Creating Objects in JavaScript

There are 3 ways to create objects.

  • By object literal
  • and By creating instance of Object directly (using new keyword)
  • and By using an object constructor (using new keyword)

Object Initialization

Use the object literal or initializer syntax to create single objects.

Example:

   var person = {

 name: "John", age: 31, 

 favColor: "green", height: 183

};

Using Object Initializers

Spaces and line breaks are not important. An object definition can span multiple lines.

Example:

var John = {

  name: "John",

  age: 25

};

var James = {

  name: "James",

  age: 21

};

Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *