Tag: HTML5

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.

var myArray = [] // Declare a new array
myArray.push("Red");
myArray.push("Blue");

var value1 = myArray.pop();
var value2 = myArray.pop();

alert(value1); // should alert the value Blue
alert(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.

var myArray = ["blue", "red", "green"];

myArray.forEach(function (x) {
  alert(x);
});

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.

var myArray = ["blue", "red", "green"];

var results = myArray.filter(function(x) {
  if (x == "blue")
      return true;
  else
      return false;
})

results.forEach(function (x) {
  alert(x);
});

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.

var myArray = ["blue", "red", "green"];

alert(myArray.some(function (x) {
  if (x == "blue")
      return true;
  else
      return false;
})); // Alerts true as 1 item in the array is blue

alert(myArray.every(function (x) {
  if (x == "blue")
      return true;
  else
      return false;
})); // Alerts false as not every item in the array is blue

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

var myArray = ["blue", "red", "green"];
var myArray2 = ["yellow", "orange"];

var 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.

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

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:

var myArray = ["blue", "red", "green"];
myArray.splice(2, 0, "yellow", "orange");

myArray.forEach(function (x) {
  alert(x);
});

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

var myArray = ["blue", "red", "green"];
myArray.splice(1, 2, "yellow", "orange");

myArray.forEach(function (x) {
  alert(x);
});

A couple of others

Sort - Sorts the array into alphabetical order

Reverse - Reverses the order of the array

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:

// local storage
localStorage.variableName = value;

// session storage
sessionStorage.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.

var myColours = [ 'red', 'blue', 'green', 'yellow'];

// Save to local storage
localStorage.colours = JSON.stringify(myColours)

// Retrieve from local storage
var 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.

try
{
  functionThatDoesntExists();
}
catch (err)
{
   alert(err.message);
}
finally
{
  //Code to execute at the end
}

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.

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