Objects

JavaScript Objects are containers that hold key/value pairs. The keys (called properties) are strings and the values can be of any type.

We can create an object either by using the Object constructor or by assigning an object literal.

var obj1 = new Object();  
var obj2 = {};

When we define an object literal we can include in it a set of properties and their associated values. Each property is given a name followed by a colon and the value associated with the property.  If multiple properties are defined in the object literal, they are separated by commas.   The name of a property is given without quotes or double quotes as they are implied.

In the example below we define an object that has 2 properties (name and age) along with their associated values.

var person = {     
    name: “Bob”,
    age: 29      // no comma after last property
};

We can add property/value pairs to an object using the dot operator.

person.IQ = 130;

We can also use bracket notation to add new property/value pairs to an object and modify the value associated with an existing property.  The identifier within the brackets can be of any type, however we use usually use strings or integers.  If the identifier within the brackets is not a string, it is automatically converted to a string with toString().

person['grade point average'] = 4.0;    // identifier can include spaces

person['0'] = "CS";  
person[1] = 20;       // 1 is converted to '1'

var a = 'age';
person[a] = 19;

The value of associated with a property can be any valid JavaScript type including other objects and arrays.

var grades = {csci105: 3.2, csci240: 4.0};
person['grades'] = grades;

var colors = ["Blue", "Brown"];
person['favorite colors'] = colors;

A value associated with a property in an object can be access using bracket notation or using the dot operator.  When using bracket notation, the identifier within the brackets must be a string.

console.log("age: " + person.age);
console.log("IQ: " + person['IQ']);

Further reading: Working with Objects

© 2018, Eric. All rights reserved.