Home

ABCs of Programming Constructs

Vital Few

Construct (verb) – to build or form by putting together simpler elements.
Construct (noun) – an object, especially a complex one formed from a number of simpler elements.

Before we talk about programming constructs, we need to discuss a few items that are related to many programming languages:

A. Commenting / Uncommenting Code

Why Comment / Uncomment Your Code:

It is important to know up front why you need to comment and uncomment code:

  1. Comment (document) your code – allows you as the name implies to make "comments" about your code. This is useful because it provides a way to capture useful information about your code, a kind of "note to self." This can come in handy when you or someone else is reviewing the code months later and need to readily figure out what the code is doing. Code that is commented will not be executed when the program runs.
  2. Debug your code – provides a mean to isolate or disable any code in question to see where the problem is occurring in your code.
  3. Disable your code – provides a way to temporarily or permanently disable code that you don't currently need or cannot currently get working but would like to keep. Otherwise, you can delete the code.
  4. Enable your code – provides a way to turn "on" a portion of your code by uncommenting it (removing the comment format) so that it execute when the program runs.

How To Add Comments To Your Code:

Most programming languages support two comment types:

  1. Single-line formatting – used for commenting out only a single line of code by prefixing the line with a double forward slash ( // ) either:
    1. On the SAME line as the code: Code will NOT execute
      // alert("Hello, World");  
    2. On a line ABOVE the code: Code will execute
      // This is a single line comment on a line above the code
      alert("Hello, World");
      (This is the preferred method because it makes the code more readable and helps to segment the code better.)

    3. AFTER the code: Code will execute AND comment will be IGNORE. It is used to write a "note to self" about the code
      alert("Hello, World");  // This will open an alert dialog box with the message "Hello, World"
  2. Block-level formatting – can be used for both single and multiple line commenting, but mostly used for multi-line commenting using the following syntax:
    /* This is a multi-line comment spanning three lines. 
    Notice the (/* and */) at the beginning and the
    ending of this comment */

TIP: There is no penalty for commenting your code; however, if you name your variables and other constructs with descriptive names you can avoid using some comments--your code becomes self-commenting or self documenting. For example, if you have a function named getEmployeeRecord, there is no need to write a common on what this function does. Many developers also include a block comment at the top of the page that typically include the purpose of the code, the creator, and any revisions made. If you write descriptive variables and functions, there is a lesser need for comments. Comments should be used to explain code that need further explanation than the code itself.

ABOUT SEMICOLON: A semicolon is used to close a statement similar to a sentence being closed with a period. This allow multiple statements to be placed on the same line if necessary (but not recommended). For example, you could write two variables (discussed later) on one line or two lines, like this:

var myVar1 = "Hello"; var myVar2 = "World";
var myVar1 = "Hello"; 
var myVar2 = "World";    

IMPORTANT NOTE: A semicolon is added to the end of a complete statement including a control structure NOT WITHIN a control structure that uses a pair of curly braces like a loop or a conditional statement (discussed later). Otherwise, you will get an error. For example:

alert("Hello, World"); // Correct closing of statement.
for(var i=0; i<10; i++) // DO NOT ADD A SEMICOLON HERE or 
 { // AFTER THE OPENING CURLY BRACE
   alert(i); // OK here
 };  // OK here

Also, while it does make a different, you should not add a semi colon to the end of a comment:
// This is a comment; (The semi-colon is not needed.)
B. Data Types / Data Casting

A DATA TYPE is as the name implies—a type of data. Data typing tells the program what specific "type" of value the variable is or can have.

ActionScript Only: Click to expand or collapse if needed

Flash support strict data typing of variables, arguments, and return values from a function. ActionScript 3 has two kind of data type:

  1. Static – checked at COMPILE time when Flash movie is published.
  2. Dynamic – checked at RUNTIME when Flash movie is played.

Data Types

While there are many data types, the six most common data types that you need to be aware of are:

  • Number –  always any type of number (whole numbers, negative number, fractions, etc.)
    • Example: a=5, a=6, x=-7 or a=7.5 While not common as the previous examples, a number can be written as an expression (i.e., var myNumber = 2+9).
    • CAUTION: If you place a number in quotes, it becomes a string.
  • String –  always in quotes – Strings can include a single character up to a complete phrase or sentence that can include letters, numbers, and whitespace characters.
    • Example: myVariable = "Hello, World", firstName = "Bob"  or lastName = "Jones". While not common as the previous example, a string can be written as an concatenation of two strings (i.e., var myString = "Hello" + " World";).
    • CAUTION: Quotes can either be single or double but they must match.  The string is the only data type that requires quotes. If you don't use quotes, the program will think you are using another type of data type instead of a string (e.g., an existing variable, array, or object)..
  • Boolean – always either true or false without quotes. Also, any non-zero number, non-empty string or non-null value are treated as true. Any object that has no initial value, 0, null, empty string (" "), undefined or NaN will be set to false. A Boolean is a special form of a numeric data type that can be represented by 0 or 1. It is typically used to store the state of a variable (e.g., what is sometimes called a flag) that can be used to "toggle" a state on or off or set a value to true or false.
    • Examples: isLightOn = true or isLightOn = false
    • CAUTION: If you place true or false in quotes, it becomes a string and they will BOTH return true
    • NOTE: Any expression that can be converted to a Boolean value can be used. (e.g., if(myObject.visible)). myObject.visible is a shorthand for myObject.visible == true)
  • Array – included in a set of square brackets "[ ... ]" and sometimes in a set of parenthesis "(...)"
    • Example: var days = ["Monday", "Tuesday", "Wednesday"];  
  • Object – always included in a set of curly braces "{ ... }" with name/value pairs
    • Example: var employee = {firstName:"Bob", lastName:"Jones"}; 
  • Constant – always retains its initial value once set so that it cannot be changed;hence the term, "constant." Best practice is to write a constant with all caps. It uses the keyword const to declare it as a constant in JavaScript. Because a constant remains "constant" (does not vary), it is not a variable.
    • Example: const PI = 3.1415;

Variables can contain various data types. In programming languages (e.g., Java and Flash), you have to decide UPFRONT that the variable will have. These languages are referred to as "strongly typed." Other languages, like JavaScript and PHP, however, you don't have to decide what data type the variable is at all. These languages are referred to as "weakly typed."  Weakly typed languages are easy to use, however, they can cause you to add a number to a string that may not return the result you want.

JavaScript support dynamic types which means the SAME variable can be used as DIFFERENT types at different times in the code:

var myVar = 5; // A number 
var myVar = "Bob" // Same variable but now a string

Boolean Examples

Because the boolean is an unusual data type, a few examples are given below on how it can be used. Typically, a boolean is used with what is called a "flag"--that is a variable that is set to a boolean and then change later in the code to "toggle" the functionality of some code. Also, it is a common naming convention to start a boolean with the prefix "is" (e.g., isGameOver).

Beginner Approach:

var lives = 3;
if (lives <1) {
alert("Game over")
}
else
{
alert("You are still alive!!")
}

If you run this code the result will be "You are still alive!!". However, if you change the variable lives to zero, the result will be "Game Over"

Intermediate Approach:

var lives = 3;
var isGameOver = (lives < 1)
if (isGameOver) {
alert("Game over")
}
else
{
alert("You are still alive!!)
}

This code executes the same as the previous code; however, the boolean variable make the "if" statement easier to read.

ActionScript Only: Click to expand or collapse if needed

Another type of number data type is int. It is used for any positive or negative integers or uint for only unsigned positive integers. Otherwise, you will want to use Number for fractions or floating numbers. It is best to use int and uint instead of the Number data type wherever possible because it will increase performance and uses less memory.

There are two other number subtypes that you can use. int is used for integer or whole numbers only and uint is used for unsigned or positive numbers.

  • NOTE: Data typing is also used to store a reference to objects (i.e., var myObject:Object = new Object()). Some classes (discussed later) can be a data type (i.e., Array, MovieClip, etc.) that are reference data types instead of primitive data types like Number, String or Boolean. While most data type are classes and need to be capitalized. Some sub-classes like "int" for integer and "uint" for unsigned integer are lowercase.
  • NOTE: A function (also discussed later) that have arguments must be data typed, (usually to a Number or a String) and if the function returns a value the function itself has to be data type.  If the function itself does not return a value, it data type is "void."
  • NOTE: Data types are actually Class and as such start with an upper-case letter (i.e., String, Number, Boolean). However, init and uint are subclasses and start with lower-case letters.
  • NOTE: There are some other fundamental data types that are used as well: Null, void and Object:
    • Null -- a variable that is declared (var myVar:Number) but not assigned a value. So it will return a null value. Not to be confuse with zero or an empty string which does have a value.
    • void -- has a undefined value. Use with functions that do not return a value.
    • Object -- used to create a generic object.
  • NOTE: There are rare cases where you can leave a variable untyped (e.g., var myVar; )  so that it can store any data type. It is best practice to use an asterisk (e.g., var myVar:* ) so that the code is implied untyped and not mistakenly untyped. Untyped variable will not create an error. Below is an instance where this can be handy:

    function createObject (type:String):*
    {
    switch(type)
    {
    case "Boolean": return new Boolean();
    case "Number": return new Number();
    case "String": return new String();
    case "Array": return new Array();
    default: trace ("Unknown type"); return null;
    }
    }
    var myObject:* = createObject("Array");
    myObject.push(1,2,3,4,5);
    trace (myObject); // Displays: 1, 2, 3, 4, 5
  • NOTE: You can check the what data type an object is with the "is" operator:
    • var firstName:String = "Hello, World";
    • trace(firstName is String) // true
  • You can also use the "typeof( )" method (e.g., trace(typeof(firstName)))

Data typing is important because you usually want to ADD a number to another number or CONCANTENATE a string to another string. Otherwise, you may get an error or the wrong data type returned. Hence, a number and a number will yield a number, a string and a number will yield a string (or a type mismatch error in some programming languages).

Data casting allows you to convert one data type to another data type.  To cast a variable to a new data type, "wrap" it with a built-in conversion function like Number() or String().

IMPORTANT CONCEPT TO REMEMBER: As a beginner programmer, it is important to remember that anything inside of a text field (e.g., string, number, or a combination of a string and number) will always be returned as a string. To prove this, there is a built-in function called typeof() that you could use to wrap around a variable to determine what type it is:

<body>
  <input type="text" id="myTextField1" value="10">
  <input type="text" id="myTextField2" value="Ten">
</body>
<script>
  var textField1 = document.getElementById("myTextField1").value;
  alert(typeof(textField1)); // Returns string
  var textField2 = document.getElementById("myTextField2").value;
  alert(typeof(textField2)); // Returns string
</script>

Returns a string
Returns a string

If you are not performing any type of calculation, this should not be an issue. However, if you need to use a value in a text field as a number, you will need to convert the text field string to a numeric value using the built-in method called Number() which as you expect converts the string numeric text value (not a string that represent a number) into an actual number:

The typeof() method has been replaced below with the Number() method:

var textField1 = document.getElementById("myTextField1").value;
alert (Number(textField1)); // Return the number 10
var textField2 = document.getElementById("myTextField2").value;
alert (Number(textField2)); // Return NaN - Not a Number
Returns 10 – a number
Returns NaN – an error of Not a Number.
C. Objects / Containers

Like real world objects, programming objects can play several "roles" at any given time:

  1. An object can be a container.
  2. A container can be an object.
  3. An object or container, well, can “contain” other objects or other containers. For example, a bowl or a cup can be a container and a bowl or a cup can also be an object. So a bowl or a cup is BOTH an object and a container.

Most programming languages support a host of built-in objects and they differ depending on their environment. For example, in a browser you have built-in objects like the window, the document, etc. Whereas, in a program like Flash, you may have other built-in objects like the stage, the timeline, etc.

In the app, we will show you how to use built-in objects and create some simple custom objects. For a more advanced study of objects, refer to other apps in the "ABCs of Programmings" series (e.g., The ABCs of OOP Objects).

Code Blocks

It is helpful to recognize that many of the programming constructs use code blocks to encapsulate their code. Code blocks are denoted by curly brackets to "open" and "close' them. Below is a list of some of these code blocks:

function functionName {   code goes here...   };
for ( loop statement)   {  code goes here...   };, do{   code goes here...    };, while {  code goes here...   };
if ( condition statement ) {   code goes here...   };
switch ( expression) { caseClause: [defaultClause:] }

NOTE: The pair of curly brackets can be on the same line or on two separate lines:

1. function functionName () {  code goes here...  };
2. function functionName () {
code goes here.....
};
3. function functionNamem ()
{
code goes here....
};

Some developers prefer number 3 because they can "see" where the code block start and end better particularly when there is a large amount of code. The is particularly true when you have code blocks nested inside of other code blocks with indentions.

CAUTION: Do not place a closing semicolon at the end of a closing parenthesis on the statement (e.g., for (), if(), switch()); otherwise, the code will not work. The semicolon goes at the end of the complete code blocks. (e.g., if (x == 5);  //This is wrong);

TIP: It is best to make it a habit to open and close a code block with right and left curly brackets first and then go back and "fill" the code block. The reason for this is that unbalanced brackets will cause a code error on the wrong line. This also holds true for using parenthesis which is used be call functions or group mathematical operations.

Operators

Operators are special symbols (e.g., =, <, >) that are place between numbers or expressions to specify "operations" that can be performed on them. These operators include:

  • assignment operation is the equal sign (=) (e.g., score = 50.),
  • math operators such as addition (+), subtraction (-), multiplication (*), and divisions( / ) (e.g., total = 5 x 5),
  • comparison operators such as greater than (>), less than (<), greater than or equal (>=), less than or equal (<=), not equal (!=) or equal (==) They are used to compare two values and will return a boolean value true or false. (e.g. score < 5)
  • Increment/decrement operators such as increment (++) or decrement (--). They are typically used as counters for loops. Where you place these operators before or after the expression will determine the output. For example:

    var x = 6;
    alert ("Increment x++ = " + x++); // results is 6
    alert ("Increment x = " + x); // results is 7

    var x = 6;
    alert ("Increment ++x = " + ++x); // results is 7
    alert ("Increment x = " + x); // results is 7

    The same holds true for decrementing:

    var x = 6;
    alert ("Decrement x-- = " + x--); // results is 6
    alert ("Decrement x= " + x); // results is 5

    var x = 6;
    alert ("Decrement --x = " + --x); // results is 5
    alert ("Decrement x = " + x); // results is 5

  • Concatenation operators use the plus sign (+) to join two or more values into a SINGLE string. For example:

    var firstName = "Bob";
    var lastName = "Jones";
    var fullName = firstName + " " + "lastName" + ": How are you doing?"
    alert (fullName) // results in "Bob Jones: How are you doing?"

    Concatenation operators can be used to join variables on separate lines using +=. For example:

    var myFullName = "Cornelius";
    var myFullName += " Chopin";
    alert (myFullName); // Results in "Cornelius Chopin

  • logical (e.g. x and y).

Operator Precedence

When working with math operators, it is important to know that when multiple operators are used in the same expression, the precedence determines the order in which the operations are performed. For example, you might think that 5 + 2 * 4 = 7 * 4 or 28. However, the correct answer is 13. The reason for this is that multiplication and division takes precedence over addition and subtraction.

However, you can OVERRIDE the order of precedence of multiple operators by placing the elements in a set of parenthesis that you want to calculate FIRST. Hence, in the previous example, if you were to add parenthesis around the 5 and 2 you would get (5+2) * 4 = 7 * 4 or 28. However, if you place parenthesis around the 2 and 4 you would get 5 + (2 x 4) = 5 + 8 or 13 which is the default in the absence of those parenthesis.

It is important also to note that when you nest parenthesis the INNERMOST parenthesis get evaluated first then the OUTTERMOST parenthesis get evaluated last. For example

5+ ((8x2) + (3x4)) = 5 + (16+12) = 28

Like real world objects, most complex programming objects are composed of simpler objects. You need to know these simpler objects before you can become proficient at creating more complex objects. In this app, you will learn the ABCs of programming constructs from the stand point of constructing (a verb) objects and building object constructs (a noun).

Many beginner developers that are just starting out programming usually will  try "a little bit of everything" to get their code to work. This can be very time consuming and frustrating and can discourage a young developer from advancing further.  However, if he or she would learn some basic programming constructs, programming can be less daunting (intimidating, overcome with fear) and in some cases it can even be fun.

Although a comprehensive understanding of programming constructs is not needed to develop many applications, having a working knowledge is definitely important to save you time and avoid being frustrated. Knowing basic programming constructs will help you program effectively and will help you learn or program in any other language as well since the only different between many programming languages are not the constructs (how the objects are created) but the syntax (how the code is written to create objects).

An experienced developer can tell how well you program by the way you program. For example, a beginner programmer has the tendency to use a lot of code starting off because he or she may to be using arrays, functions, objects, and other constructs to make the code more efficient. However, an experienced developer may use a fraction of the number of lines of code than a beginner developer. Even though the output of the program may display the same, the underlying code and speed of the program will be different. This is why is is so important to learn basic programming construct upfront when starting to learn how to program.

As a beginner developer, you don’t start off programming a lot of code. You typically GROW in your programming skills something like this:

  1. You will learn basic programming constructs
  2. You will then use other people code (OPC) because you are not comfortable writing your own
  3. You will also use pre-built code (class libraries) for common programming tasks (i.e., interaction, special effects (f/x), animation, 3D, etc.).
  4. You may also use code generators or templates so that you don’t have to write code yourself
  5. You will become proficient in a given language (e.g., JavaScript)
  6. You may learn how to program using Object Oriented Programming (OOP) which makes it easier to program
  7. You will then want to (or have to because of your job) learn a new language (e.g., PHP)

NOTE: While class libraries, templates, and code generators are good, there is no substitute from learning how to program your own code.

Emphasis in this app is placed on learning programming constructs without cluttering the code with a lot of statements. As a result, the alert() method is used to "trace" the result of these programming constructs. You are free to replace the simple alert statements with your own code based on your programming experience. Also, JavaScript is used as the base programming language; however, most of the constructs (maybe with syntax differences) can be transferred to other programming languages.

< Previous Topic     Next Topic >