//INIT: Using objects

<New code>

//INIT: var objectName = {};
— define an empty object

//INIT: objectName.propertyName = propertyInfo;
— set the propertyName of objectName to propertyInfo
//INIT: objectName[ 'propertyName' ] = propertyInfo;
— set the propertyName of objectName to propertyInfo
//INIT: objectName{ propertyName: propertyInfo };
— set the propertyName of objectName to propertyInfo

Objects and Properties

Let's say I have pet chicken.

It's name is Prince Rupert the Second, it is dark brown, it has long feathers and is 2 years old.

I can store this information in the following (slightly awkward) ways:

1. Using a different variable for each property (time consuming)

var chickenName = "Prince Rupert the Second";
var chickenColour 	= "dark brown";
var chickenFeathers 	= "long";
var chickenAge 		= 2;

console.log(	// output the chicken information
	"My chicken's name is " 
	+ chickenName 
	+ ". It is " 
	+ chickenColour 
	+ " with " 
	+ chickenFeathers 
	+ " feathers. It is " 
	+ chickenAge 
	+ " years old."
);

2. Create an object with a series of properties (elegant & fast)

var chicken = {}; // define as an empty object
			
chicken.name 		= "Prince Rupert the Second";
chicken.colour 	= "dark brown";
chicken.feathers	= "long";
chicken.age 	= 2;

console.log(
	"My chicken's name is " 
	+ chicken.name
	+ ". It is " 
	+ chicken.colour
	+ " with " 
	+ chicken.feathers
	+ " feathers. It is " 
	+ chicken.age
	+ " years old."
);

Assigning properties to an object

There are several ways to assign properties to an object. First, define your variable as an empty object:

var chickenObject = {}; // define as an empty object

Then you can assign values to each property. Each of the following methods is exactly the same:

chickenObject.name 	= "Wilbur";
chickenObject.feathers 	= "long";
chickenObject[ 'name' ] 		= "Wilbur";
chickenObject[ 'feathers' ] 	= "long";
chickenObject = { name: "Wilbur", feathers: "long" };
chickenObject = {
	name: 		"Wilbur",
	feathers: 	"long"
};

Reading properties of an object

Once the property values are stored, then you can get the information out again. Each of the following methods is exactly the same:

console.log( chickenObject.name );
console.log( chickenObject['name'] );

Objects and function pipelines

One of the reasons why programmers love objects is because they organize a lot of information under one variable. This means that you can pass them easily between functions in a function pipeline.

var mainProcedure = function () {
	var inputObj 	= getInfoObject();		// note that this function returns an object
	var outputString	= processTheObject( inputObj );	// note that this function accepts an object as an argument
	outputInfo( outputString );
}

Learn more

Code example


Address maker

Please enter the address information into the blanks below:
Name:
Street address:
City:
Province:
Postal code:

The address you entered was:


...is made with the following code:

<!doctype html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>drapak.ca - Computer Programming 12: INIT - Using objects</title>
        <meta name="description" content="Learn how use objects in Javascript">
        <meta name="author" content="Dave Drapak">
        <!--
            Change log:
                18. October 2015    -created
                4. April 2017       - reworked to move script to tail
        -->
        <style>
            input, button {
                position:   absolute;
                left:       20em;
            }
        </style>
    </head>
    <body>
        <h2>Address maker</h2>
        <p>
            Please enter the address information into the blanks below:<br>
            Name: <input id="nameID" type="text" value="Citadel High School"><br>
            Street address: 
            <input id="streetID" type="text" value="1855 Trollope Street"><br>
            City: <input id="cityID" type="text" value="Halifax"><br>
            Province: <input id="provinceID" type="text" value="Nova Scotia"><br>
            Postal code: <input id="postalCodeID" type="text" value="B3H 0A4"><br><br>
            <button id="buttonID">Click me!</button>
        </p>
        <p>
            The address you entered was:<br><br>
            <strong id="outputID"></strong>
        </p>

        <script>
            var mainProcedure = function () {
                console.log( 'in mainProcedure...' );
                var inputObj        = getInput();
                var outputString    = createAddressString( inputObj );
                outputAddress( outputString );
            }
            
            //INPUT: read the value of each input line and return an object the information
            var getInput = function () {
                console.log( 'in getInput...' );
                var inputObj    = {};
                
                inputObj.name           = document.getElementById('nameID').value;
                inputObj.street         = document.getElementById('streetID').value;
                inputObj.city           = document.getElementById('cityID').value;
                inputObj.province       = document.getElementById('provinceID').value;
                inputObj.postalCode     = document.getElementById('postalCodeID').value;
                
                return inputObj;
            }
            
            //PROCESS: accept an object, and then combine properties to make an HTML address
            var createAddressString = function ( inputObj ) {
                console.log( 'in createAddressString, inputObj:' + inputObj );
                var outputString    = inputObj.name
                                    + "<br />"
                                    + inputObj.street
                                    + "<br />"
                                    + inputObj.city
                                    + "<br />"
                                    + inputObj.province
                                    + "<br />"
                                    + inputObj.postalCode;
                return outputString;
            }
            
            //OUTPUT: display the HTML string inside #outputID
            var outputAddress = function ( outputString ) {
                console.log( 'in outputAddress, outputString:' + outputString );
                document.getElementById('outputID').innerHTML   = outputString;
            }
            
            //INPUT: trigger main procedure when #buttonID is clicked
            document.getElementById("buttonID").onclick = mainProcedure;
        </script>
    </body>
</html>

Another example: Creating an election graph