X
HOME HTML CSS JAVASCRIPT SQL PHP JQUERY XML ASP.NET MORE...
REFERENCES | EXAMPLES | FORUM | ABOUT

JavaScript Objects


Objects are just a data, with added properties and methods.


Object Properties and Methods

Properties are values associated with objects.

Methods are actions objects can perform.


A Real Life Example. A Car Object.

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

Object Properties Methods

car.name = Fiat

car.model = 500

car.weight = 850kg

car.color = white

car.start()

car.drive()

car.brake()

car.stop()

All cars have the same properties, but the property values differ from car to car.

All cars have the same methods, but they are performed at different times.



JavaScript Objects

In JavaScript, objects are data (variables), with properties and methods.

Almost "everything" in JavaScript are treated as objects. Dates, Arrays, Strings, Functions....

In JavaScript you can also create your own objects.

This example creates an object called "person", and adds four properties to it:

Example

var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};

Try it Yourself »

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

Example

var person = {
    firstName:"John",
    lastName:"Doe",
    age:50,
    eyeColor:"blue"
};

Try it Yourself »

There are many different ways to create new JavaScript objects.

You can also add new properties and methods to already existing objects.

You will learn much more about objects later in this tutorial.


Accessing Object Properties

You can access the object properties in two ways:

Example

name = person.lastName;
name = person["lastName"];

Try it Yourself »


Accessing Object Methods

You can call an object method with the following syntax:

objectName.methodName()

This example uses the fullName() method of a person object, to get the full name:

Example

name = person.fullName();

Try it Yourself »

Object methods are ordinary JavaScript functions defined as object properties.

You will learn much more about functions later in this tutorial.

Note
Objects written as name value pairs (lastName: "Doe") is similar to:

Associative arrays in PHP.
Hash tables, hash maps or hashes in C, C++, C#, Java, Perl, and Ruby.
Dictionaries in Python.



Your suggestion:

Close [X]

Thank You For Helping Us!

Your message has been sent to W3Schools.

Close [X]
Search w3schools.com:

WEB BUILDING

Download XML Editor FREE Website BUILDER Free HTML5 Templates

SHARE THIS PAGE

facebook