Objects are JavaScript's fundamental data structure. An object is just a container for a collection of named values (aka properties).
Objects in JavaScript fall into four groups:
An object is very similar to an array but with the difference that you define the keys yourself. It is not limited to using only numeric indexes but can use keys as your want, such as first_name, age, and so on.
Let's take a look at a simple array and object.
var myarr = ['red', 'blue', 'yellow', 'purple'];
Below is the index and the values as key/value pairs of above array.
Key Value 0 red 1 blue 2 yellow 3 purple
The below variable hero is an object.
var hero = { breed: 'Turtle', occupation: 'Ninja' };
To define object use { and } and separate the elements (called properties) contained in the object with commas
For example these are all the same:
var o = { prop: 1 }; var o = { "prop": 1 }; var o = { 'prop': 1 };
The quotes are necessary for the names of the properties for some cases like below.
var o = { something: 1, 'yes or no': 'yes', '!@#$%^&*': true };
This is a valid object. The quotes are required for the second and the third properties, otherwise you will get an error.
An object contain properties. In arrays, we say that they contain elements(no difference between the terminology elements and properties).
A property of an object can contain a function, because functions are just data.
In the below example 'talk' property is a method.
var dog = { name: 'Benji', talk: function() { alert('Woof, woof!'); } };
It's also possible to store functions as array elements and invoke them.
var a = []; a[0] = function(what){alert(what);}; a[0]('Boo!');
In some programming languages, a normal array, also called indexed or enumerated (the keys are numbers) and an associative array, also called a hash (the keys are strings)
JavaScript uses arrays to represent indexed arrays and objects to represent associative arrays. If you want a hash in JavaScript, you use an object.