Home

ABCs of Programming Constructs

Data Containers

VARIABLES, ARRAYS, and PROPERTIES are all CONTAINERS for DATA (or a COLLECTION of DATA) to be placed in the computer memory. Where they differ is the amount and type of data they can contain.

A. Variables

Variable – is a container to store a reference to a SINGLE data type. A reference is code in a computer memory that can be "refer" to later easily.

There are several actions usually done first when creating a variable in this order:

  • DECLARE IT: the key word var is used to declare it as a variable.
    • EXAMPLE: var
    • EXCEPTIONS: You will see later that you can pass a variable as a function's parameter. In which case, you do not use the "var" keyword (e.g., function myFunction (myVar)). Also, once you declare a variable you should not use the var keyword again when referring to that variable elsewhere in the code; if you do re-declare a variable, you will get the same result as the first instance unless you changed its value again.
  • NAME IT: a name is given to it.
    • EXAMPLE: var firstName
      • A descriptive name is typically used. While var a = l*w is correct to use, it does not easily convey the meaning of the variables. Instead var area = length * width gives meaning and clarity to the variables. So the more descriptive you are, the easier and faster it is for you or someone else to read your code.
      • no spaces are used in variable name (e.g., cannot use first Name)
      • must begin with a letter and not a number (e.g., cannot use 1firstName)
      • cannot use a reserved word that is used by the programming language (e.g., function), otherwise, you may get an error.
      • can only use alphanumeric characters with the dollar sign ($) or underscore (_). Some programming languages (e.g., jQuery, PHP) require you to start a variable with a dollar sign ($).
      • It is common practice to use what is referred to as camelCase where you start with a lowercase letter and then use an uppercase for every other word in the name (e.g., getTotalScore). TIP: When writing in camelCase, just remember where ever you intent to put a SPACE put a CASE (uppercase, that is.)
      • name is case-sensitive (e.g., myVar is different from myvar).
  • ASSIGN IT: an equal sign (=)—technical term is an assignment operator—and a value may be assigned to the variable.
    • EXAMPLE: var firstName = “Bob”
  • CLOSE IT: a semicolon (;) is used to close the variable statement. Optional in some programming languages like JavaScript, but highly recommended.
    • EXAMPLE: var firstName = “Bob”;
    • While adding semicolons are optional in JavaScript, you should be aware that the semicolon is required in some programming language (i.e., Java). As a result, you may want to make it a habit if you use other languages. So, if you move between programming languages you would be less likely to inadvertently forget to include them.
    • The semicolon is also used so that you can add more than one statement on a single line. However, this is typically not recommended.
    • However, be careful to place a semicolon at the end of a statement or end of a complete code block.

MEMORY TIP: DNA - Declare, Name, and Assign. Closing is optional but highly recommended in JavaScript.

NOTE: Flash and some other programming languages also require you to type the variable:
TYPE IT: a colon (:) and a data type name is used to define variable type (Flash and some other languages)

    • EXAMPLE: var firstName:String
    • The data type name denotes this variable as a string and not a number or any other data type.


Use of semicolon: Click to expand or collapse for detail

You will see later that many programming constructs (e.g., function, loop, etc.) use curly braces ("{code goes here....}") that complete what is termed a code block (A code block, well, is a block of code that gets executed as a group). Not adding a semicolon at the end of the code block will generate a subtle error that may not be obvious to a beginner developer. For example, this code will throw an error because the semicolon is not at the end of the code block for the function:

function helloWorld();
  {
    alert("Hello,World");
   };

The correct way is:

function helloWorld()
  {
    alert("Hello,World");
  };

The reason for this is because many programming construct (in this case, a function) and its curly braces make a complete statement. To see this better the previous code block could have been written on a single line like this:

function helloWorld() 
  {
    alert("Hello,World");
   };

FLASH ONLY: You do not have to add semicolons in Flash because it will automatically add them for you. This is an advantage because as mentioned earlier, you can inadvertently place a semicolon in the wrong place and Flash will throw an error. When you click on the Auto Format button, Flash will automatically insert all semicolons into your code for you.

A variable can be DECLARED, NAMED, ASSIGNED and CLOSED all at the SAME time:

var lastName = “Jones”;    

Or, it can be declared, named and closed but assigned at a LATER time when it is needed in the code:

var lastName;
// more code goes here...
lastName = “Jones”

If a variable is created and not assigned a value, it will result in the word undefined if traced with a built-in function like alert().

var lastName;
alert(lastName); // Returns undefined  
When to use variables effectively: Click to expand or collapse for detail

See another app in this series called ABCs of OOP Objects for more details on object oriented programming.

While variables are good to use, you will see later that they are not always needed when dealing with objects. They are best used when you want to store a reference of a large piece of code (e.g., an object or an object and its property) in a variable with a descriptive name that better represent that object particularly if it is used multiple times later in the code. For example, you could write a variable to store a reference to a element like this:

1. Reference to an object (with an id of footer_copyright):

var footerInfo = document.getElementById("footer_copyright");
footerInfo.innerHTML = "Something else";

You can now use that object (itself) reference multiple places in your code easily.

2. Reference to an object and its property (with an id of footer_copyright and a property of innerHTML):

var footerInfo = document.getElementById("footer_copyright").innerHTML;
footerInfo = "Something else";

You can now use that object property reference multiple places in your code easily.

3. No variable at all (object is declared and assigned a value and used only once in your code):

However, if you only needed to use the code once, you could have just combine the two techniques above:

document.getElementById("footer_copyright").innerHTML = "Something else";

The advantages of using a variable to store a reference to other code that is used repeatedly is that it makes your code:

  • harder to NOT make typing mistakes because there is only one place you need to make a change in your code
  • easier to read because you will be reading the short descriptive name of the object or object/property and not the long reference to it throughout your code
  • easier to update because there is only one place you need to make an update to your code.
    NOTE: The reason for these advantages is that you only have to update the variable declaration and any reference throughout the code will reflect that change. For example,

GIVE EXAMPLE HERE OF SOME CODE WITH MULTIPLE REFERENCES TO THE SAME VARIABLE.

 

Numerical/String Variables: Click to expand or collapse for detail

Numerical Variables:

Numerical variables can use simply arithmetic operations (+, -, *, / and %) to perform operation on a set of numbers or a number and another numeric variable

var myNumbers=2+5;  or var myNumbers = 2 + 5;

NOTE: It is common practice to include spaces around around assignment operators and arithmetic operators as in the second example to make the code easier to read.

The percent (%) operator is called modulus assigns a remainder to a variable. It is useful when you want to determine if a value that is returned is even or odd so that you could create alternating row colors, etc.

var myNumber1 = 5;
var myNubmer2 = 2;
var myNubmer3 = myNumber1 % myNumber2; 
alert(myNubmer3); // Returns  a reminder of 1

Numerical variables can also use special operators (++) or (--) to increment or decrement a value by one. Or by using (+=) or (-=) with a specific increment or decrement value

EXAMPLES:

To increment or decrement by ONE, use "++" or "--":

var myNumber = 5;
myNumber ++;
alert(myNumber) // Returns 6;
var myNumber = 5;
myNumber --;
alert(myNumber) // Returns 4;

To increment by MORE THAN ONE, use "+=" or "-=":

var myNumber = 5;
myNumber += 2;
alert(myNumber) // Returns 7; 
var myNumber = 5;
myNumber -= 2;
alert(myNumber) // Returns 3;    

The "*=", "/=" and %= can also be used but is less common.

CAUTION: Be careful not to put spaces between the two symbols; otherwise, code will not work (e.g., += and not + =).

Operator Precedence

When using more than two numeric values with operators to perform an arithmetic expression, the operator precedence is important to take into consideration. Like traditional mathematics, the order is:

  1. Multiplication (*)
  2. Division (/)
  3. Addition (+)
  4. Subtraction (-)

In the following example, the myVar variable with resolve to 110 because 20 will be multiply by 3 first (60) and then added to 50. (Instead of the 50 being added to 20 (70) and then multiply by 3 resulting in 210.)

var myVar = 50 + 20 * 3; 
alert(myVar); // Results 110

However, when using parentheses, the operations inside the parentheses are calculated first.

var myVar = (50 + 20) * 3; 
alert(myVar); // Results 210

When operations have the SAME precedence (e.g., addition and subtraction), they are calculated from left to right:

var myVar = 50 + 20 - 3; 
alert(myVar); // Results 67

String Variables:

String variables are not added but concatenated by using the "+" or "+=" concatenate operators:

var myString1 = "Hello,";
var myString2 = " World";
var myString3 = myString1 + myString2;
alert(myString3); // Returns "Hello, World";
myString3 += " and Goodbye, World."; alert(myString3) // Returns "Hello, World and Goodbye World."

Adding Strings and Numbers

As seen earlier, adding two numbers will return a number. However, adding a number with a string will return a string:

var NumberOrString  = "5" + 5; 
alert(NumberOrString) 
// Returns string concatenation of  "55" instead of 10
B. Arrays

Array – is a container for an "array" of MULTIPLE data types including other arrays. In contrast, string and numeric variables are sometimes called SCALAR because they can only hold a single data type. There are two type of arrays: Indexed and Associative. An indexed array REFERENCE its array elements by its index number starting from zero. Whereas, an associative array REFERENCE its array element by is associated name instead of number.

An array is a special variable (notice it starts with the keyword var) that is created by using a set of square brackets so that it can hold MULTIPLE elements of different data types separated by commas. This type of array is called a literal array (as opposed to an associative array discussed later).

  • Example: var myArray = [5, "lastName", true, ["this", "is","another", "array"], {property:value}, VarArrayOrObjectFunction ]
  • An array is a great way to "see" the various data types side-by-side and how they are formatted:
    • A number will always be a number without quotes (e.g., 5)
    • A string will always have single or double quotes (e.g., "lastName")
    • A boolean will always be the lowercase true or false (e.g., true)
    • Another array may be in square brackets (e.g., ["this", "is","another", "array"]) or a reference to an existing array name (e.g., myArray).
    • An object may be in curly braces (e.g., {property:value}) or a reference to an existing object name (e.g., myObject).
    • A function may have a function syntax (e.g., function()) or a reference to an existing function (myFunction).
    • A word without quote refers to another existing variable, array, object, or function that has been previously defined  (e.g., VarArrayOrObjectFunction)

Why use an array. Well, you could use a series of variables like this:

var fruit1 = "apple";
var fruit2 = "banana";
var fruit3 = "orange";
var fruit4 = "grapes";

The problems with multiple variables is that it requires a lot of individual variables each with a different variable name (e.g., fruit1, fruit2, etc.) and you cannot loop around them easily. This is where an array comes in handy. In fact, arrays and loops are "kissing cousins" because you see them together all the time.

Or, you could group these multiple related variables into a single array like this:

var myFruits = ["apple", "banana", "orange", "grapes"];
alert(myFruits);  // Returns apple, banana, orange, grapes

And then loop around this array to get to its elements. (Looping will be discussed later.)

Another way to create a literal array is to use the new constructor. However, the previous example is preferred and the most common format.

var myFruits = new Array("apple", "banana", "orange", "grapes");
alert(myFruits); // Returns apple, banana, orange, grapes

CAUTION: You should avoid using the new constructor when creating an array because you may not get the result you expected. For example, if you create an array like this:

var myArray = [10]; 
alert(myArray); // Returns an array with one element with a value of 10.

However, if you create an array like this, you may not get the results you expected.

var myArray = new Array(10);
alert(myArray); // Returns an array of 10 undefined elements ( ,,,,,,,,,, )

CAUTION: Also, be careful not to place a comma after the last element in a literal array or you make get an error.

While there is one property of an array (e.g., length) that returns the total number of elements in an array, there are dozens of methods. However, the two most popular methods are the push() and pop().

Adding elements to an array:

While you typically add elements you need to an array when you create an array (See example above), there are times when you may want to add a new element to an array after it has been created.

You could use the array's square bracket alone with an index value to add an element to an array and then assign it a value.

var myFruits = ["apple", "banana", "orange", "grapes"];
myFruits [4] = "watermelon";
alert(myFruits); // Returns apple, banana, orange, grapes,watermelon

However, this is not the best method because you may not always know what the last index value is readily if the array is large or if the array is coming from an external source.

var myFruits = ["apple", "banana", "orange", "grapes"];
myFruits [8] = "watermelon";
alert(myFruits); // Returns apple, banana, orange, grapes,,,,, watermelon

CAUTION: Notice the five commas (,,,,,) in the return because the fourth through seven indexes were "SKIPPED OVER."

Array length property

So, the easiest way to ensure that you add an element to the end of an array is to use the array's length property. While properties and methods will be discussed in more detail later, they will be discussed briefly here.

To get an array's length, use the array name followed by a period and then the length property:

var myFruits = ["apple", "banana", "orange", "grapes"];
alert(myFruits.length); // Returns 4 because that is the number of elements in the array. 

As a result, you can use the length property to ascertain the total number of elements in an when you want to ADD an element to the end of an array using the following format:

var myFruits = ["apple", "banana", "orange", "grapes"];
myFruits[myFruits.length] = "pear";alert(myFruits); // Returns apple, banana, orange, grapes, pear 

The length property also prevents you from inadvertently added elements that will creates "undefined" element in the array:

var myFruits = ["apple", "banana", "orange", "grapes"];
myFruits[10] = "pear";
alert(myFruits) // Returns apple, banana, orange, grapes,,,,,,,, pear 

Notice the extra commas denote empty elements. If you attempt to access an element that is empty, you will get an undefined error.

var myFruits = ["apple", "banana", "orange", "grapes"];
myFruits[10] = "pear";
alert(myFruits[8]) // Returns undefined

While using the length property is good to add a SINGLE element to the end of an array, you can use another method called push() to add MULTIPLE elements to the END of an array:

var myArray = ["One", "Two", "Three"]
myArray.push("Four", "Five")
alert(myArray); // Returns One,Two,Three, Four, Five

While the push() method will add elements to an array, if traced, it will can be used to return the total number of elements like the length property. However, it is best practice to use the length method:

myArray = ["One", "Two", "Three"]
alert(myArray.push("Four")) 
// Returns 4alert(myArray); // Returns One,Two,Three, Four

Removing elements from an array:

The pop() method REMOVE ONE ELEMENT from the END of an array. Unlike, the push() method which ADDS one or more elements to the END of an array.

var myArray = ["One", "Two", "Three"]
myArray.pop();
alert(myArray); // Returns One,Two

Like the push() method, the pop() method  can also return the name of the element that was removed from an array:

var myArray = ["One", "Two", "Three"];
alert(myArray.pop()); // Returns Three

NOTES ON ADDING AND REMOVING ELEMENTS:

  • Since the push() and pop() methods both will add or remove the last element in an array, it is best to have these method return some useful information when executed (the number of elements in an array or the name of the element that was deleted from an array.)
  • While push() and pop() will add or remove elements at the END of an array, respectively. Unshift() and Shift will add or remove elements to or from the BEGINNING of an array, respectively. However, these methods are not used as often as push() or pop() because the order is usually not important where the element is added. When removing an element from an array, you typically assigned it to a variable (e.g., var removeStudent = student.pop() ).  To remove all elements in an array, you can create a loop with a pop() method in it. Like the push () method, the unshift () method can be used to add multiple items to beginning or an array.
  • It is important to note that the push and unshift methods after executing their command returns the number of items that are in an array.
  • Notice that the push() method require a parameter and the pop() method does not. Other array methods are use to sort, add/remove from the front of the array, add/remove in between the array elements, etc.

Array sort() method

Since the order of the elements in an array is the order in which they were written, there are times when you may need to sort the elements in the array from A-Z or Z-A. To sort elements in an array, use the array name followed by a period and then the sort method( ):

var myFruits = ["apple", "banana", "orange", "grapes"];
alert(myFruits.sort()); // Returns  apples, banana, grapes, oranges

Accessing elements in an array:

Once an array is created, you will have need of accessing elements in the array. To do this, you have to use a number to "index" the array to get an element. The important thing to remember is that arrays are zero-based indexed which mean that you get to the first element by starting with the number zero instead of the number one when using the array access operator:

var myFruits = ["apple", "banana", "orange", "grapes"];
myFruits [0]; // apple
myFruits [1]; // banana
myFruits [2]; // orange
myFruits [3]; // grapes

As mentioned earlier, arrays are often used with loops. So, it is important to know how many elements there are in an array to determine how many times to loop around it.

While using the technique above is OK, it is common practice to loop around an array to get to all of its elements at one time. While looping will be discussed later, below is a typically syntax to loop around an array using a "for" loop and the array length property discussed earlier:

var myFruits = ["apple", "banana", "orange", "grapes"];
for (var i=0; i< myFruits.length; i++)
  {
    alert (myFruits[i]); // Returns apple, banana, orange, grapes
  }

Array Properties and Methods

The real power of JavaScript arrays are the built-in array properties and methods. See w3Schools for detail examples of array properties and methods.

Key Characteristics of Arrays

It is important to remember the following characteristics about an array:

  • An array is a special variable that can hold multiple data types. Notice in the examples above, it uses the var keyword to declare it as a variable.
  • While you can place multiple data types in an array, an array is typically used to hold an "array" or list of related elements.
  • An array is most of the time identified by the square brackets. If you create an array from a Class (discussed later), you will use parenthesis instead of square brackets (e.g., var myArray = new Array(5, true, "Bob");).
  • The most important property of an array is its length that is typically used with a loop.
  • An array is zero-based index which means that to get to the first element in the array you start with the number zero instead of the number one.
  • Arrays and loops are "kissing cousins" because you see them together most of the time.
  • Because an array is just a special variable, it has the same name conventions as a variable.
  • An array is treated as an object. If you wrap the array in the typeof() method, it will return an object.
  • You typically CREATE and POPULATE an array at the SAME time.
  • If you place an array inside of an array, you create what is known as multi-dimensional arrays that is used to emulate a table-like or database-like structure where the OUTER array represents the COLUMNS and the INNER array represents the ROWS.
    GIVE EXAMPLE HERE OF A MULTIDEMINSIONAL ARRAY
ActionScript Only: Click to expand or collapse for detail

Vector – is a container for a MULTIPLE data of a SINGLE type.

    • Example: myVector = ["firstName", "lastName", "Address"] // A vector with multiple values of the same type--in this case, a string.

Array vs. Object: Click to expand or collapse for detail

Many programming languages (e.g., PHP) support another type of array called an associative (or hash) array. It is similar to a literal array; however, instead of accessing its elements with number indexes, you access elements with named indexes.

Like a regular array, an associative array elements are separated by commas like a literal array but have name/value pairs that are separated by COLONS. The ORDER of the elements in an array are preserved when displayed. In an object, the order of the elements are in alphabetical order.

They are called associative arrays because they associate names to values to create a set of property/value pairs for an object. Regular arrays only use simple values instead of pair values.

However, associative arrays cannot use the array length property or other array methods (e.g., sort, join, slice) because they only applies to numeric indexes. Hence, elements added using named indexes can only be treated as properties of the array object and not true array elements. In addition, a regular array uses a "for" loop but an associative array uses a "for...in" loop because it is treated as an object.

There is no problem with adding properties to an array object using associative array syntax since that how properties are added to an object in JavaScript.

JavaScript used a number index to create an element:

var myArray = ["Bob", "Jones"];
myArray[2] = "Engineering"; alert(myArray[2]); // Returns Engineering

However, you cannot create an element from a named index like this:

var myArray["firstName"] = "Bob"; 

However, you can create an object and assign properties to it:

var myObject = new Object(); 
myObject.firstName = Bob; myObject.lastName = 'Jones';

Or, you could create an object literal and assign properties at the same time:

var myObject = {firstName: "Bob", lastName: "Jones"};

You can access properties of this object with either the dot syntax (myObject.firstName) or the array syntax (myObject["firstName"]) . You can loop through its properties with a for…in loop:

var myObject = new Object();
myObject.firstName = "Bob"; myObject.lastName = "Jones";
for (var index in myObject)  
    {
      alert("property = " + index + ", value = " + myObject[index]); 
      // Returns property = firstName, value = Bob 
      // Returns property = lastName, value = Jones
    }
C. Properties

Property – is a container to store references to VARIABLES of an object. The key phrase is "of an object." Hence, properties only refer to objects.

While a variable is a container for a SINGLE data type; an array is a container for MULTIPLE data type. A property is a container for PROPERTIES of an object data type.

Before, we see how properties are variables of an object, we must first create an object programmatically. More details on objects can be found if you click the menu item Blueprints / Object Containers:

var myEmployee  = { firstName: "Bob", 
                                    lastName: "Jones", 
                                    position: "Engineering"
                                   };
alert(myEmployee.firstName);  // Returns "Bob"

Note that objects are variables too (see keyword "var") but it can hold multiple values. Like arrays, there are two ways to create an object. Here is another way:

var myEmployee  = new Object ();
myEmployee.firstName = "Bob";
myEmployee.lastName = "Jones";        
myEmployee.position =  "Engineering";
alert(myEmployee.firstName);  // Returns "Bob"

In the above example, firstName, lastName, and position are variables of the myEmployee object. While NOT correct coding, it may be helpful to write the code in a manner so that you can "see" these variables better. Notice how the colons were replaced with equal signs:

var myEmployee  = { firstName = "Bob",
                                   lastName  =  "Jones",									      
                                   position =  "Engineering"
                                  };
alert(myEmployee);  // Returns "object Object"
alert(myEmployee.firstName); // Returns "Bob"

Properties are variables of an object much like methods are functions of an object (See Action Containers menu).

IMPORTANT NOTE: It is important to note that you don't talk the the object directly (e.g., myEmployee); otherwise, you get "object Object". You talk to a property of an object (e.g., myEmployee.firstName) to get a property value.

Key points to remember about variables:

  • A variable is NOT a data type, it is a container for a data type. It is akin to a toy box—a toy box is not a toy, it is a container for toys.
  • A variable is actually a location in the computer's memory where you store data as a specific data type.
  • A variable once created is placed in the computer memory.
  • A variable is an INVISIBLE object and cannot be "seen" unless its value is displayed through another VISIBLE object (e.g., a text field).
  • Once a variable has been set, it can be used elsewhere in your code by using its name without the var keyword.
  • Once a variable is declared using the var keyword, it CANNOT be declared again anywhere else in the code; otherwise, you will get an error.
  • If you do change a variable's value later, it will be reassigned that new value in the computer memory.
  • Variables (as well as some other containers) as the name implies can VARY or change over time. Unlike CONSTANTS which never changes (e.g., PI)
  • Variables are usually declared at the TOP of the code so they can be easily changed if necessary.
  • Once a variable (e.g., var myVar = "Hello, ");) is used somewhere in the code it is evaluated or resolved at that point in the code and you get the variable’s value (“Hello, ”) and not  its name (myVar) at that point in the code. So, for the previous variable mentioned, the result of myText = myVar + "World." is actually RESOLVED to myText = "Hello, World."
  • A variable's VALUE can be set or retrieved. This is typically known as "setter" or "getter":
    • SET: To set (or change) a variable's value, you assign it one. (e.g., var firstName = "Bob";) See below for details.
    • GET: To get a variable's value of an object, you use the object and its property (e.g., myObject.height) and store it in a variable (e.g., myObjectHeight = myObject.height) See another app in this series called ABCs of OOP Objects for details.
< Previous Topic     Next Topic >