Arrays

Javascript Arrays are an object that permits you to store multiple values into a collection for easy reference. For example, if you wanted to track a user’s position position over some time, you could insert the x and y values into an array. Arrays are more than just the example of x and y values though.

Let’s say we are building a calculator. Initially, we might think that we only need to variables. We need one for the first number before the operator is pressed and another one after. Congratulations on us being super static. Maybe we now want to be able to add more than just 2 values before calculating the sum. We should have used an array from the very beginning. If we would have used an array, we could have put all of those numbers in one single array, which is a 1000 times better than having to create a new variable for each number. It is a compliment in the world of programming if someone says your coding is dynamic. Arrays are in fact just that, dynamic.

Example
var example = new Array(“aa”,”bb”,”cc”);
example[3] = “dd”;
example[4] = “ee”;
document.write(example); // write out our entire array
document.write(“<br/>”); // line break
document.write(example[2]); // write out array item with an index of 2
Result
aa,bb,cc,dd,ee
cc

Common Array Properties

constructor – tells us the function that created the Array object’s prototype

Example
var example = new Array(“aa”,”bb”,”cc”);
document.write(example.constructor);
Result
function Array() { [native code] }

length – returns the total number of items in a array

Example
var example = new Array(“aa”,”bb”,”cc”);
document.write(example.length);
Result
3

Common Array Methods

As an object, arrays have a variety of methods. Since arrays are super dynamic, we have a lot of things we want to do with them. The creators of JavaScript gave us plenty of methods to use on our arrays.

concat() – this is the proper way to combine multiple arrays

Example
var example1 = new Array(“aa”,”bb”,”cc”);
var example2 = new Array(“dd”,”ee”,”ff”);
var example3 = new Array(“gg”,”hh”,”ii”);
var example4 = example1.concat(example2,example3);
document.write(example4);
Result
aa,bb,cc,dd,ee,ff,gg,hh,ii

indexOf() – finds item and returns it’s position

Example
var example = new Array(“aa”,”bb”,”cc”,”cc”);
document.write(example.indexOf(“cc”));
Result
2

lastIndexOf() – finds item’s finale occurrence and returns it’s position

Example
var example = new Array(“aa”,”bb”,”cc”,”cc”);
document.write(example.lastIndexOf(“cc”));
Result
3

join() – joins all of the elements in an array into a string (values separated by a comma)

Example
var example = new Array(“aa”,”bb”,”cc”);
document.write(example.join());
Result
aa,bb,cc

slice() – selects and returns part of an array

Example
var example = new Array(“aa”,”bb”,”cc”,”dd”);
document.write(example.slice(2,4)); 
Result
cc,dd

reverse() – reverses the order of the array

Example
var example = new Array(“aa”,”bb”,”cc”);
document.write(example.reverse());
Result
cc,bb,aa

sort() – sorts elements as you would expect

Example
var example = new Array(“dd”,”cc”,”bb”,”aa”);
document.write(example.sort()); 
Result
aa,bb,cc,dd

splice() – add and/or removes elements from array

Example
var example1 = new Array(“aa”,”bb”,”cc”,”dd”);
example1.splice(2,1);
document.write(example1);
document.write(“
“); // line break

var example2 = new Array(“aa”,”bb”,”cc”,”dd”);
example2.splice(1,1,”ee”,”ff”);
document.write(example2);
Result
aa,bb,dd
aa,ee,ff,cc,dd

push() – adds items to the end of array, and returns position of the added item

Example
var example = new Array(“aa”,”bb”,”cc”);
document.write(example.push(“dd”));
Result
4

pop() – removes and returns the last item of the array

Example
var example = new Array(“aa”,”bb”,”cc”);
document.write(example.pop()); 
document.write(“
“); // new line
document.write(example);
Result
cc
aa,bb

shift() – removes and returns the first item of the array

Example
var example = new Array(“aa”,”bb”,”cc”);
document.write(example.shift()); 
document.write(“
“); // new line
document.write(example);
Result
aa
bb,cc

unshift() – adds item to beginning of the array and returns its new length

Example
var example = new Array(“aa”,”bb”,”cc”);
document.write(example.unshift(“zz”)); 
document.write(“
“); // new line
document.write(example);
Result
4
zz,aa,bb,cc

XMLHttpRequest Object

For now, let’s discuss what an AJAX XMLHttpRequest Object is. It is an object that we use in AJAX that allows us to talk to a server behind the users back. This object is the sole reason we are allowed to make updates into the user’s page without forcing them to reload the entire page. An HTTP Request is actually sent out by your browser each time you type a website, which is then sent to a server that finally sends you back the web page. Of course, this happens right before your eyes and you know what it is doing. The XMLHttpRequest is very much like that, but it is very sneaky. The XML is simply a reference to the data structure that is being returned. Now, we can vent about Internet Explorer. Don’t get me wrong. I love Microsoft, but I absolutely hate the tyranny it has on developers. I will vent my anger more as we move through this tutorial.

Let’s make an XMLHttpRequest:

Example var xmlhttp;
if (window.XMLHttpRequest)
{ // works with IE7+, Chrome, Firefox, Safari
xmlhttp=new XMLHttpRequest();
}
else
{ // works with IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}

It is the else statement that annoys me about Internet Explorer. However, you can see that they now have jumped on the bandwagon and started using XMLHttpRequest. Now, we can start sending requests to the server.

To GET Or To POST?

I won’t go into much detail here, but GET is usually the best because it is faster. However, you might want to use POST when you are transferring a very large amount of data. GET actually has a limit to the maximum allowed size for a url.

We will only deal with the GET

Example //PHP File <?php
echo $_GET[‘sampleVar’];
?>
//end PHP File
//HTML File
<script type="text/javascript">
function doGET()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() //This part is actually executed last
{
if (xmlhttp.readyState==4 && xmlhttp.status==200) // Was the request processed successfully?
{
document.getElementById("sampleDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajaxTest2.php?sampleVar=" + Math.random());
xmlhttp.send();
}
</script>
<button type="button1" onclick="doGET()">GET</button>
<div id="sampleDiv">Nothing is here</div>

Obviously, call the function doGet() by clicking our button1. In that function, we have the standard setting up of our xmlhttp variable, creating the actual XMLHttpRequest. Next, we skip over the xmlhttp.onreadystatechange=function().

When then prepare to send our request with xmlhttp.open(“GET”,”ajaxTest2.php?sampleVar=” + Math.random(),true);. Let’s break this down a little bit. The “GET” is the request type. The ajaxTest2.php is the url that we are going to talk with. After the separating ?, we have a variable, sampleVar that is equal, =, to our Math.random(). The Math.random() simply generates a random number between 1 and 0. We use this so that our changed page won’t be cached by the browser. Finally, we send the request with xmlhttp.send();.

Eventually, the xmlhttp.onreadystatechange=function() will fire when the request returns with data. In that function, we set our sampleDiv‘s content equal to our returned data, xmlhttp.responseText, which in this case is whatever our Math.random() is. As you can see, every time you click the button the Math.random() variable is sent to the PHP file that spits out the variable’s value into the sampleDiv container.

Ajax Introduction

AJAX stands for Asynchronous JavaScript and XML. It is a complete game changer when it comes to user experience. Normally, web pages are loaded one at a time. When a user wants more content, they click a link. With AJAX, a user can click something and content can be loaded into the page, using JavaScript, without reloading the entire page.

Essentially, the user does some event that fires off an AJAX HttpRequest after an XMLHttpRequest object has been created. The server then processes the HttpRequest, and returns the data back to the browser. Now without JavaScript, it would be entirely worthless unless you were posting data to a database. We will set up our AJAX so it calls a JavaScript function, known as a Callback Function, to use our returned data from the server in the next tutorial.

Why Use jQuery Instead?

Learning AJAX is a great feat for any developer, but when it comes to developing, it is usually best to keep it simple. jQuery already has methods of JavaScript functions that do almost everything AJAX can do. What’s the point in rewriting long code that is already available to you? There isn’t. So, if you really love the fundamental understanding of programming read the AJAX tutorials. If not, read the AJAX tutorial under jQuery.

Operators

JavaScript Operators are pretty standard. They are exactly what you would expect from your high school math class. Operators are anything you use when comparing or acting upon with numbers/values.

Arithmetic Operators:

Example
<html>
    <body>
        <script type="text/javascript">
            var y = 7;  //Setting our variable
            var x = y + 2; //Addition, x would equal 9 here
            var x = y - 2;  //Subtraction, x would equal 5
            var x = y * 2;  //Multiplication, x would equal 14
            var x = y / 4;  //Division, x would equal 1.75
            var x = y % 3;  //Modulus (Divison Remainder), x would equal 1
        </script>
    </body>
</html>

Incrementing and Decrementing JavaScript Operators

Incrementing is adding 1, while decrementing is subtracting 1.

Example
<html>
    <body>
        <script type="text/javascript">
            var w = 0;
            var x = 0;
            var y = 0;
            var z = 0;
            document.write("w++ = " + w++); //Writing our results
            document.write("<br/>"); //Writing a line break
            document.write("x-- = " + x--); //Writing our results
            document.write("<br/>"); //Line break
            document.write("++y = " + ++y); //Writing our results
            document.write("<br/>"); //Line break
            document.write("--z = " + --z); //Writing our results
        </script>
    </body>
</html>
Result

w++ = 0
x– = 0
++y = 1
–z = -1

Incrementing and decrementing is a somewhat difficult concept, so take a deep breath and relax. We have a standard document.write method happening. In that method, we have a string that is showing you which variable we are talking about. So, the “w++ = “ is a string and not a variable. Then, we add that string to the w++ variable that is being incremented. (Quick Note: Strings can be combined with integers using the +, however, if you were to try to combine two integers in this manner, it would give you the sum of them.) The important part here is the order of the increment or decrement operator. Notice how incrementing the w, as in w++, gives you the result of 0, but incrementing the y, as in ++y, gives you the result of 1. This is because it is an increment operator has two options. Since the increment operator is after the w, as in w++, it needs incremented after the statement has been performed, while ++y is incremented before the statement is performed, since the ++ is before the y.

Let’s try to clear up that String + integer part really quick:

Example
<html>
    <body>
        <script type="text/javascript">
            var string1 = "You are awesome, ";
            var string2 = "and you know it.";
            var string3 = string1 + string2;
            document.write(string3);
        </script>
    </body>
</html>
Result
You are awesome, and you know it.

So, that is how you combine two strings.

Example
<html>
    <body>
        <script type="text/javascript">
            var x = "7";
            var y = 7;
            var example1 = x + x;
            var example2 = y + y;
            var example3 = x + y;
            var example4 = y + x;
            document.write("Example1 = " + example1);
            document.write("<br/>"); //Line break
            document.write("Example2 = " + example2);
            document.write("<br/>"); //Line break
            document.write("Example3 = " + example3);
            document.write("<br/>"); //Line break
            document.write("Example4 = " + example4);
        </script>
    </body>
</html>
Result
Example1 = 77
Example2 = 14
Example3 = 77
Example4 = 77

First off, the document.write(“Example1 = ” + is just writing out a string “Example1 = ” and combining that with our returning variable. So, example1 returns 77 because the string “7” + “7” is simply the joined of a string into “77”. Next, example2 returns 14 because the integer 7 added to the integer 7 equals 14. Finally, example3 returns 77 because the string 7 is combined with the integer 7, and the only way JavaScript knows how to join and integer and a string is by joining them like two strings. The same is true for example4

Assignment Operators

These are not a necessity for programmers, but they are great shortcuts.

Example
<html>
    <body>
        <script type="text/javascript">
            var x = 4;
            var y = 2;
            x = y;  //x = 2
            x += y;  //x = 6, (this is the same as x = x + y;)
            x -= y;  //x = 2, (this is the same as x = x - y;)
            x *= y;  //x = 8, (this is the same as x = x * y;)
            x /= y;  //x = 2, (this is the same as x = x / y;)
            x %= y;  //x = 0, (this is the same as x = x % y;)
        </script>
    </body>
</html>

References

If Statements

If your new to programming, this will be a great tutorial for the fundamentals of programming logic. An if statement is one of a few ways to do something when a condition is set. It helps control the flow of your coding logic.

In English:

If you are thirsty, take a drink.

 

We are just going to assume that from now that the code in the examples are embedded in the <script> tags that are in the body of an HTML document.

Example
var thirsty = true;
var drank = false;
if(thirsty == true)  //notice the ==
{
    drank = true;
    document.write(drank);
}
Result
true

The == is one of the comparison operators. It is not the same as = that sets a variable or property equal to something. Since, the variable thirsty does equal true the if is executed. If the statement would have said if(thirsty == false), drank would not have been set to true.

Example
var x = 7;
if(x===7)
{ 
    //this would be executed
}
if(x==="7")
{
    //this would not be executed because === is a strict operator that makes sure that the variable is set to the correct value and type of the conditional variable. The conditional variable here is is "7"
}
if(x!=8)
{
    //this would be executed because != means that the variable is not equal to the conditional variable
}
if(x>8)
{
    //Since 7 is not greater 8, this would not be executed
}
if(x<8)
{
    //Since 8 greater 7, this would be executed
}
if(x>=7)
{
    //Since 7 is equal 7, this would be executed
}
if(x<=6)
{
    //Since 7 is not less than or equal to 6 this would not be executed
}

The comparison operators are extremely useful, but they are not just restricted to integers. For example, if(x == “example”) would return false, since 7 is not equal to the string “example”.

Example
var x = 7;
if(x>=6 && x<=8)
{
    //Since 7 is greater than 6 and is less than 8, this statement would be executed
}
if(x==7 || x>=8)
{
    //This if statement says if x is equal to 7 or if x is greater than 8, then execute this statement. While x is not greater than 8, x is equal to 7; therefore, it will execute the statement.
}
if(!(x==6))
{
    //Since x is equal to 7 and we are checking if that statement is false, this statement would be executed.
}

If statements can be just as simple as the examples above, but they can also be more useful when you combine the if statements with else if and else.

Example
var x = 6;
if(x == 8)
{
    x++;
    document.write("if(x = 8) and now x = " + x);//This would not be executed because x is not equal to 8
}
else if (x == 7)
{
    x = 4;
    document.write("else if (x = 7) and now x = " + x);//This would not be executed because x is not equal to 7
}
else
{
    x = 20;
    document.write("else and now x = " + x);//This would be executed because the other conditionals were not met
}
Result
else and now x = 20

You might be asking yourself, “What is the point in an else if statement?” Well consider the following examples

Example
var x = 8;
if(x == 8)
{
    x++;
    document.write("if(x = 8) and now x = " + x);//This statement would be executed because x is equal to 8
}
if (x == 7)
{
    x = 4;
    document.write("else if (x = 7) and now x = " + x);//This statement would not be executed because x is not equal to 7
}
else
{
    x = 20;
    document.write("else and now x = " + x);//This statement would be executed because the other conditionals were not met
}
Result
if(x = 8) and now x = 9
else and now x = 20

Why did the if(x == 8) and the else both execute their statements? It is best to think of ifs as completely separate conditionals, but else if and else build off whichever if they follow. So, if you had an if statement that was following by and another if statement, the first if statement would be separate from the second if statement just like the example above. However, the second if statement in the example above, has an else built onto it. Since the first if statement’s condition is satisfied, it executes its statements. The second if statement’s condition is not satisfied, but its built on else statement’s condition is satisfied. Therefore, x is incremented in the first conditional, and “if(x = 8) and now x = ” + x is displayed on the screen. Also, we have the second if’s else that sets x equal to 20, and “else and now x = ” + x is displayed on the screen.

References