JavaScript Objects JAVASCRIPT

JavaScript Objects  

JavaScript Objects

JavaScript Objects

Real-Life Objects, Properties, and Methods

In real life, a car is an object. A car has properties like weight and color, and methods like start and stop:

You have already learned that JavaScript variables are containers for data values.

This code assigns a simple value (Tesla) to a variable named car:

var car = "Tesla";

Objects are variables too. But objects can contain many values.

This code assigns many values (Tesla , Cybertruck , white) to a variable named car:

var car = {type:"Tesla ", model:"Cybertruck ", color:"Gray"};

Example

var car = {type:"Tesla", model:"Cybertruck", color:"Gray"};

Object Definition

You define (and create) a JavaScript object with an object literal:

var person = {firstName:"Deepak", lastName:"Chahar", age:22, eyeColor:"blue"};

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

var person = {
  firstName: "Deepak",
  lastName: "Chahar",
  age: 22,
  eyeColor: "blue"
};

 

Example

var person = {
  firstName: "Deepak",
  lastName: "Chahar",
  age: 22,
  eyeColor: "blue"
};

Accessing Object Properties

You can access object properties in two ways:

objectName.propertyName

or

objectName["propertyName"]

Object Methods

Objects can also have methods. Methods are actions that can be performed on objects. Methods are stored in properties as function definitions.

var person = {
  firstName: "Deepak",
  lastName : "Chahar",
  id       : 2121,
  fullName : function() {
    return this.firstName + " " + this.lastName;
  }
};

 

The this Keyword

In a function definition, this refers to the "owner" of the function.

In the example above, this is the person object that "owns" the fullName function.

In other words, this.firstName means the firstName property of this object.

 

Accessing Object Methods

You access an object method with the following syntax:

objectName.methodName()

Example

name = person.fullName();

If you access a method without the () parentheses, it will return the function definition:

name = person.fullName;

Download free E-book of JAVASCRIPT


#askProgrammers
Learn Programming for Free


Join Programmers Community on Telegram


Talk with Experienced Programmers


Just drop a message, we will solve your queries