//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 chickenObj = {}; // define as an empty object
			
chickenObj.name 		= "Prince Rupert the Second";
chickenObj.colour 	= "dark brown";
chickenObj.feathers	= "long";
chickenObj.age 	= 2;

console.log(
	"My chicken's name is " 
	+ chickenObj.name
	+ ". It is " 
	+ chickenObj.colour
	+ " with " 
	+ chickenObj.feathers
	+ " feathers. It is " 
	+ chickenObj.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 chickenObj = {}; // define as an empty object

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

chickenObj.name 	= "Wilbur";
chickenObj.feathers 	= "long";

chickenObj[ 'name' ] 		= "Wilbur";
chickenObj[ 'feathers' ] 	= "long";

chickenObj = { name: "Wilbur", feathers: "long" };

chickenObj = {
	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( chickenObj.name );
console.log( chickenObj['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 () {
	//the getInfoObject function returns an object
	var inputObj 	= getInfoObject();	
	
	//the processTheObject function accepts the object as an argument
	var outputString	= processTheObject( inputObj );	

	//the outputInfo function accepts the string variable 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: 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                                   - Drapak
                4. April 2017       - reworked to move script to tail           - Drapak
                27. October 2018    - reworked style and clarified code         - Drapak
        -->
        <style>
            input, button {
                position:       absolute;
                left:           20em;
            }
            #outputId {
                font-weight:    bold;
            }

        </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>
            <span id="outputId"></span>
        </p>

        <script>
            //OUTPUT: display the HTML string inside #outputId
            var outputAddress = function ( outputString ) {
                console.log( 'in outputAddress, outputString=' + outputString );
                
                document.querySelector( '#outputId' ).innerHTML = outputString;
            }
            
            //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;
            }
            
            //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.querySelector( '#nameId' ).value;
                inputObj.street         = document.querySelector( '#streetId' ).value;
                inputObj.city           = document.querySelector( '#cityId' ).value;
                inputObj.province       = document.querySelector( '#provinceId' ).value;
                inputObj.postalCode     = document.querySelector( '#postalCodeId' ).value;
                
                return inputObj;
            }
            
            //MAIN: make the functions connect the data together
            var mainProcedure = function () {
                console.log( 'in mainProcedure...' );
                
                var inputObj        = getInput();
                var outputString    = createAddressString( inputObj );
                outputAddress( outputString );
            }
            
            //INPUT: trigger main procedure when #buttonId is clicked
            document.querySelector( "#buttonId" ).onclick   = mainProcedure;
        </script>
    </body>
</html>

Another example: Creating an election graph