Working with Javascript Objects and Arrays
 
 

JavaScript is more than just strings and numbers. JavaScript lets you create objects and arrays. Objects are similar to classes. The objects are given a name, and then you define the object's properties and property values. An array is an object also, except arrays work with a specific number of values that you can iterate through. This article discusses how to create and work with objects including arrays. 

Working with JavaScript Objects

Before you can write an object variable, you should understand the premise of an object. An object defines a set of properties related to a specific part of your application. For instance, if you have an ecommerce site, you have different parts of your site related to the store. You have customers, orders, products, and information related to these objects. Let's take a customer, for instance. A customer has an address, phone number, first name and last name. The amount of properties for a customer is up to you and how you design your application. But, let's start with creating a customer object with some standard properties.

var customer = {

            first_name: 'Joe',

            last_name: 'Smith',

            phone: '999-999-9999'

};

We've seen the "var" keyword before. This keyword tells JavaScript that we're creating a variable. In this example, we've created a custom object named "customer." We've then created properties named "first_name," "last_name," and "phone." After the colon, we've defined values for these properties. 

What if you don't have data that you want to use for an object? No problem. JavaScript lets you create standard objects without defining any custom data on-the-fly. The following code also creates a customer object, but the data isn't filled until after the object is created. 

var customer = new Object();

customer.first_name = 'Joe';

customer.last_name = 'Smith';

customer.phone = '999-999-9999';

Notice that this code instantiates the internal "Object()" object. This is the base object to create custom objects within your code. This object gives you the ability to instantiate an object without giving it any data. Both methods work for your JavaScript code, and you can instantiate an object as many times as you need to fill a database with information. You can also return data to the web page and print it on the user's browser. This will involve using a new method we haven't seen yet. 

The "document" object contains a number of methods that help you interact with a web page's HTML. We'll discuss JavaScript with HTML in later chapters, but the "document.write()" method is convenient when you want to test your JavaScript code. Let's take the previous customer object and print it on the web page. 

document.write(customer.first_name);

document.write("<br/>");

document.write(customer.last_name);

The above statement writes the customer's first and last name to the web page. This snippet of code is used to give you an example of how you can return data you stored in an object's properties. If you notice, the code that prints the text on the web page is similar to the customer object. That's because the document object is native to the JavaScript language. This object contains several properties and methods that you'll use to interact with a web page's document object model (DOM). We'll discuss the DOM in later lessons.

The Array Object

If you've performed any kind of programming before, you might be familiar with arrays. In JavaScript, an array is another object you use to hold values. Instead of assigning and calling properties, an array lets you call values using an index. An index describes the location of a value stored in memory. With an array object, you defined the number of values you want to store, and retrieve these values based on their associated index. It's important to remember that arrays start at the index 0. The index 0 is the first element of an array, the index 1 is the second element, index 2 is the third value, and so on.

Let's start off with defining an array. The following code defines an array that will hold three values.

var customer = new Array(3);

Notice that the number 3 in the array parenthesis indicates the number of values that the array can hold. However, again the values start with an index of 0. This concept is important to remember when assigning and retrieving values. You can also assign values to an array in the same way you assign them immediately in an object. The following code also creates a "customer" array but also assigns data to each array index. 

var customer = [

            'Joe',

            'Smith',

            '999-999-9999'

];

Again, the above code holds three values. The first name is assigned the index of 0, last name is assigned index 1, and the phone number is given index 2. 

Let's go back to the first array code. We've assigned a variable named "customer" to the "Array" object that allows for three values. Now, let's assign values based on index number. Look at the following code. 

var customer = new Array(3);

customer[0] = 'Joe';

customer[1] = 'Smith';

customer[2] = '999-999-9999'; 

Notice that instead of assigning values on-the-fly, we've assigned values based on the index numbers. These index number serve not only the purpose of assigning values, but also a looping purpose. You can use loop structures to streamline your coding process and iterate through each array value based on its index. Let's take the following code as an example. 

for (int j = 0; j < 3; j++)

{

Interested in learning more? Why not take an online JavaScript course?

            document.write(customer[j]);

}

We discussed for loops in the previous chapter. For loops tie in with arrays in most programming languages. Notice that instead of calling an index by number, we use the j variable. The j variable is initialized with the value 0 in your opening for loop structure, so the first loop returns the value held in the customer array's index 0. The loop returns and j is incremented by 1. Now, j has a value of 1, so the JavaScript code prints out the value held in the array's 1 index or the second value, which is the customer's last name. Finally, the loop returns again, j is incremented again, and now j has a value of 2. The value (phone number) is printed to the web page. Now that j is incremented to 3, it is no longer less than three, which is the condition that must be met for the for loop to continue. The for loop exits and you've iterated through all values of your array. This type of loop and its logic is widely used across JavaScript and other programming languages, so it's a good idea to practice with this type of coding when you're a beginner. 

Multidimensional arrays are also a big part of programming. You can think of multidimensional arrays as a matrix. For each row, there are a number of columns. Let's use the multiplication table as an example. Let's keep it simple and just use three rows and three columns. With this matrix, we have 9 values. You'll use multidimensional arrays with embedded for loops. Take a look at the following code example. 

var row = new Array(3);

for (int j = 0; j < 3; j++)

{

            row[j] = new Array(3);

            for (int k = 0; k < 3; k++)

{

            row[j][k] = j * k;

}

}

The above code is more complex than the previous example. The first line of code defines the number of rows for the multiplication table. Remember, the number 3 defines the number of values but the index numbers are 0 to 2.

The for loop creates a new array for each row. This new array is used for the columns in our multiplication matrix. The embedded loop with the k variable loops through each column and assigns a value to the row's columns. The main outer loop continues for 2 more runs and creates a multiplication table. 

Arrays and objects are common in most JavaScript apps. When you work with libraries such as AngularJs or KnockoutJs, you'll use objects extensively. Objects also allow you to customize your JavaScript structures as you define them on your web pages. Use objects to represent the properties and information on your pages, so they are more easily readable when you need to document or edit your code.

Defining Functions and Methods

Functions are a major part of modular code. Functions are typically used when you have JavaScript code you need to run on multiple pages. Build a function and you just need to include the function file once in your code. Then, all you need to do is call that function from each page in your web application. Methods are similar to functions, except methods are functions included in a class. Methods can be inherited as part of an object-oriented class. Some JavaScript classes are pre-built within the JavaScript language, or you'll need to work with methods from external libraries. This lesson discusses functions and methods and how you can work them into your JavaScript code. 

Creating and Calling a Function 

The more basic of the two items we'll learn in this lesson is the JavaScript functions. Functions are the code snippets you want to run several times either in one web page or several. For instance, if you need to calculate the multiplication of two variable numbers several times in your code, it's probably better to build a function that takes two variables, multiplies the two numbers, and then returns the result. 

Take a look at the following code. 

function MultiplyNumbers(n1, n2) {

    return n1 * n2;          

}

The first line of code defines the function. The word "function" indicates to JavaScript that you're about to define a function. The next part "MultiplyNumbers" is the name of the function. You'll need this name each time you want to call the function. The two variables in parenthesis are the variables you must pass to the function. If you don't pass two variables when you call the function, an error is displayed. Next, the function code is defined. In this example, there is only one line of code in the function. The return statement returns the product of the two variables. 

Now you need to call the function from your JavaScript code. Since this function returns a value, you need to assign the function's result to a variable. Look at the following code. 

var result = MultiplyNumbers(8, 6); 

The above code defines a new variable named "result" and calls the MultiplyNumbers function. In this example, two numbers are passed to the function, 8 and 6. The two variables are multiplied, and the result 48 is returned and assigned to the result variable. 

You don't always need to return a value. JavaScript also supports functions that just perform expressions and don't return a value to the calling JavaScript code. For instance, suppose you just want to multiply two numbers and print the results to the screen. The following code uses the same function process but does not return a result. 

MultiplyNumbers(8, 6);

function MultiplyNumbers(n1, n2) {

    document.write( n1 * n2 );          

}

Notice that there is no return statement in the above example. The function has the same name, and it still multiplies the two values you pass to it. The only difference is that this function writes a result to the screen versus return the value to the calling function to assign the result to a variable. 

Object-Oriented JavaScript: Creating Methods 

JavaScript supports object-oriented code. This means that you can build classes with properties and methods similar to Java, C++ or C#. The only difference is the syntax. In the previous code example, the function uses "document.write()". The "write" function is a method in the "document" class object. You can also make custom objects and add methods to work with specific parts of your code and web page. 

Let's take a "customer" object. A customer probably has a first and last name, and this customer probably wants to edit information. The customer first and last name variables are properties of the object. Editing information is a method. You know how to build your classes with properties and methods by evaluating which one performs an action and which one is a static property of the object. If the definition is that an action is performed, you make a method. If the value describes the object, use a property. 

Let's first create the class. The following code creates a simple customer class. 

var Customer = function (first_name, last_name) {

            this.first_name = first_name;

            this.last_name = last_name;

};

The above code creates properties for the "Customer" object, but you still need to create an "Edit" action. In this example, the action will change the customer's first and last name. The following code adds a method to the Customer object. 

var Customer = function (first_name, last_name) {

            this.first_name = first_name;

            this.last_name = last_name;

};

Customer.prototype.Edit = function (first_name, last_name) {

            this.first_name = first_name;

            this.last_name = last_name;

};

Notice the second part of the code defines the "Edit" function. This function also takes the first and last name information and assigns the new information to the method's local variables, first_name and last_name. We give this method an action name, because methods are supposed to perform actions on a class object. 

Now, when we want to use this method, we first define a Customer object in our JavaScript code and then call it using the method name. The following code shows you how to work with a custom object and its method. 

var myCustomer = new Customer('Jim', 'Smith');

myCustomer.Edit('James', 'Smith');

In the above code, a Customer object is created with the name "Jim Smith," but then the customer later changes his name to "James." The "Edit" method is called within the Customer class where the customer can change his name. 

Lexical Scoping

When you work with object-oriented coding, scope is important for your variables. Your variables can either be local or global. A global variable is available anywhere in the code, but a local variable is accessible only within the function. Let's first look at global variables. We can even use the MultiplyNumbers function. Look at the following function code. 

var number1 = 8;

MultiplyNumbers(6);

function MultiplyNumbers(n2) {

    document.write( number1 * n2 );          

}

Notice this time we declared a "number1" variable. This variable is global, because it's not contained within any function code. The function still uses the variable and writes 48 on the screen. The function can use the variable since it's global. Again, global variables can be used anywhere in the code. 

Now let's take a look at a local variable using the above function.

var number1 = 8;

MultiplyNumbers(6);

function MultiplyNumbers(n2) {

   var number1 = 6;

    document.write( number1 * n2 );          

}

As you can see, we have two "number1" variables.  The first one is the global variable we used in the previous example. The next one is a local variable. Local variables can only be used within the local function, so what is written to the screen when you run the document.write() method? The answer is 64. The local variable overrides the global variables. In some languages, an error is thrown when you define two variables with the same name. However, with JavaScript, you can use the same local variable name and create a variable that is accessible only within the function. 

The scope of your variables is important when working with functions. If you call a variable or function that isn't accessible, an error is thrown by the JavaScript engine. This type of coding is classed in object-oriented JavaScript, but you'll need to dive deeper into classes and object-oriented coding to fully understand how these variables work. You need to work with constructors and inheritance, which we will cover in the next lesson. 

Understanding how to work with functions makes your code much more efficient. Instead of multiplying variable numbers several times, you just call this function once. You can also place your functions in a separate JavaScript file and add the file to your HTML code. The following code shows you how to add a function .js file to your HTML pages. 

<script src="myfunctions.js"></script> 

You would place your function code within the JS file and then call the function anywhere within the JavaScript. Adding the above code into your pages lets you call any function stored in the file as if the function was written on the page. This method also makes your code better readable, and if you decide to change any functionality within a function, you only need to change the functionality once and not on several pages. 

Practice with functions and return values to get a better feel of how these functions work to manipulate values in your code.