Web Development

HTML5 Series - Array

If your going to do any sort of JavaScript programming it's not going to be long until you have to work with an array, so there's a few array functions you need to know about.

Push and Pop
Push and Pop are functions that add and remove items from an array. The easiest way to understand what they are doing is to imagine your array as a stack of paper. When you push and item onto the array it's the same as putting it on the top of your pile. When you Pop an item off it's the same as taking the top item from the pile.

1var myArray = [] // Declare a new array
2myArray.push("Red");
3myArray.push("Blue");
4
5var value1 = myArray.pop();
6var value2 = myArray.pop();
7
8alert(value1); // should alert the value Blue
9alert(value2); // should alert the value Red

Foreach loop
Probably one of the most useful functions for an array is the for each loop. A for each loop is essentially calling a function for each item in the array (hence for each). This is particularly useful in all kinds of scenarios.

1var myArray = ["blue", "red", "green"];
2
3myArray.forEach(function (x) {
4 alert(x);
5});

Filter
As the name suggests filtering is a way to find items in your array. If you know C# then it works in a similar way to a lambda expression. The filter function takes a parameter of a function. Like the forEach loop the function is called on each item in the array, the function must then returns either true or false depending on if the filter criteria matched.

In this example notice that the result of myArray.filter is being assigned to another variable. This is because applying the filter wont actually remove items from the myArray array.

1var myArray = ["blue", "red", "green"];
2
3var results = myArray.filter(function(x) {
4 if (x == "blue")
5 return true;
6 else
7 return false;
8})
9
10results.forEach(function (x) {
11 alert(x);
12});

Some, Every
The some and every functions can be used to see if some items in the array match a criteria of if all of them do. They return either true or false.

Like the filter function, a function is passed as the criteria and returns either true or false.

1var myArray = ["blue", "red", "green"];
2
3alert(myArray.some(function (x) {
4 if (x == "blue")
5 return true;
6 else
7 return false;
8})); // Alerts true as 1 item in the array is blue
9
10alert(myArray.every(function (x) {
11 if (x == "blue")
12 return true;
13 else
14 return false;
15})); // Alerts false as not every item in the array is blue

Concat
Concat is used to combine 2 arrays into 2 new array.

1var myArray = ["blue", "red", "green"];
2var myArray2 = ["yellow", "orange"];
3
4var myArray3 = myArray.concat(myArray2);

Slice
Slice lets you create a new array from an existing by letting you specify the start and end item. Those items and the others between then form the new array.

1var myArray = ["blue", "red", "green"];
2var myArray2 = myArray.slice(2, 3); // selects red and green
3

Splice
Splice can be used to add and remove items in an array. The function has the syntax:

arrayName.splice(index, how many, items to add);

Note: the index value starts at 0.

For example in our colour array we could add yellow and orange in between red and green with the following:

1var myArray = ["blue", "red", "green"];
2myArray.splice(2, 0, "yellow", "orange");
3
4myArray.forEach(function (x) {
5 alert(x);
6});

Alternatively we could replace red and green with yellow and orange.

1var myArray = ["blue", "red", "green"];
2myArray.splice(1, 2, "yellow", "orange");
3
4myArray.forEach(function (x) {
5 alert(x);
6});

A couple of others

Sort - Sorts the array into alphabetical order

Reverse - Reverses the order of the array

jQuery ajax

If you want to dynamically load content into your page chances are your going to need to do some sort of request to a server in the background. The simplest way of doing this is to use jQuery's ajax function.

Here's an example of a GET request and a POST request:

1$.ajax({
2 type: "POST", // Set the HTTP type to POST
3 url: "/serviceurl.aspx", // URL of the service
4 data: "{data: [{"Field1": 1}] }", // Data to be posted to the service
5 processData: false, // If set to true the data will be processed and turned into a query string
6 success: (function (result) {
7 // Result of the service call
8 }),
9 error: (function (jqXHR, textStatus, errorThrown) {
10 alert(errorThrown);
11 })
12});
13
14$.ajax({
15 type: "GET", // Set the HTTP type to GET
16 url: "/serviceurl.aspx", // URL of the service
17 dataType: "jsonp", // Set what type of data you want back
18 success: (function (result) {
19 // Function that will be called on success
20 })
21});

HTML5 Series - Web Storage

One of the best benefits of HTML5 particularly for Web Apps is the ability to store data locally within the users browser. This means in many places you can speed your Web App up by fetching data once and then retrieving it locally in the future, rather than going back to a server each time.

There are 2 types of storage available localStorage and sessionStorage. The simple difference is that localStorage doesn't expire while sessionStorage expires at the end of the users session.

Both types store data in a key/value list and could not be simpler:

1// local storage
2localStorage.variableName = value;
3
4// session storage
5sessionStorage.variableName = value;

One thing to note though is you can only store text. If you want to store something more complex the simple solution is to convert it to and from JSON. E.g.

1var myColours = [ 'red', 'blue', 'green', 'yellow'];
2
3// Save to local storage
4localStorage.colours = JSON.stringify(myColours)
5
6// Retrieve from local storage
7var retrievedColorus = JSON.parse(localStorage.colours);

HTML5 Series - Error Handling

One thing you can say for certain about writing code is at some point your going to write something that error's. It may be picked up in code reviews, or by a tester, and then fixed but for certain as you are human at some point you will make a mistake. What's important though is what happens after the mistake.

If your a C# developer then good news JavaScript has the same try, catch, finally functionality that C# has and it works in the same way.

Wrap you code that could error with a try statement and curly braces and following it add in a catch statement with the code that you want to execute in the event of an error. Finally if you want some code to execute either way after both, place this in the finally block.

1try
2{
3 functionThatDoesntExists();
4}
5catch (err)
6{
7 alert(err.message);
8}
9finally
10{
11 //Code to execute at the end
12}

Notice the catch section is passed a parameter and I am then alerting a property of this called message. The error parameter can be useful for debugging what actually went wrong and contains a few other parameters.

  • Description
  • Message
  • Name
  • Number
  • Stack

Sometimes you may also want to cause an error to be thrown. You may be asking why, but consider people calling your functions may in-fact pass values that are not valid. You could detect this and throw an error containing some useful information before there incorrect parameter values causes your code to error and a less helpful message given.

1var err = new Error(1, "Oh dear, that's not going to work"); // First parameter is the error number, second is the message
2throw err;