The HTML5 Diaries – Part 4 – Javascript Core Capabilities

This is the fourth post in this blog series, covering the Microsoft 70-480 HTML5 certification. This blog post will discuss Javascript. If you have no idea what this series is about, and want to know more about the Microsoft 70-480 certification, click here. If you want to go to the first article in the series, click here.

So, Javascript… It’s a weird language. It’s got nothing to do with Java, but is called Javascript. Its proper name is “ECMAScript”, but acronym ECMA doesn’t exist anymore. It’s got its share of warts and carbuncles. However, it’s not all bad. It’s known as the assembly language of the internet. We use it for adding interactivity to web pages. There are cool libraries like knockout.js and jquery. You can write server side code with it, using node.js. Javascript is cool.

And if you’re going to develop HTML5 applications you’re going to need to know it. I’m only going to talk about the basics of the language here. Declaring variables and arrays. Manipulating arrays. Methods. Functions. Object oriented programming in Javascript. Nothing too heavy. Javascript is a big language, and it’s a lot to cover in one blog post. If you want to read more, be sure to pick up a copy of Douglas Crockford’s “Javascript: The Good Parts”. It’s nice and concise, and it gives a good low down of the language. Also, Crockford is the guy behind JSLint; A cool little site that allows you to do a static analysis of your code to get an understanding of its quality.

With all that said, let’s begin.

Javascript is a dynamic, weakly typed language. What does that mean? Well, if you’ve ever used Java, C or C#, you might have noticed that you declare a variable with a type (bool, string, char, int) and if you have an integer, you can’t force a string in there. Javascript isn’t like that. The way you declare a variable is a little bit different too:

var a = 10;

Here, you’ve created a variable called ‘a’ which holds a value of ten. If you wanted to, you could later assign ‘a’ a value that might be a string, or boolean value. Javascript is cool like that, y’see. We’re going to talk about arrays a bit more now. Arrays are basically lists of variables. You can declare them really easily.

var a = [];

Populating arrays is simple too.

var fruit = [“apples”, “oranges”, “lemons”, “kiwi”];

And, JavaScript has a lot of cool little methods that allow you to manipulate and interact with these arrays. So, suppose you want to echo out every single element in that fruit array you created before?

log(fruit);

All elements echoed out will be comma separated. Want to echo every element in that array in alphabetical order? That’s fairly easy.

log(fruit.sort());

The next two examples will make sense if you’re familiar with the concept and the terminology of “The Stack”, but for this example, I’ll spare you the computer science lecture. Suffice to say that if you want to add elements to the array, you “push” it onto the stack, and if you want to remove an element from the array, you “pop” it.

A quick demo. Popping the stack:

fruit.pop();

And pushing an item onto the stack:

fruit.push();

Now, suppose you wanted to merge your fruit array with a vegetables array? Easy as pie. Just use the concat method.

fruit = fruit.concat(vegetables);

If you wanted to select all elements in an array in between two indexes, there’s a function for that.

fruit = fruit.slice(0, 1);

And if you want to replace a couple of elements, you can simply splice them.

fruit.splice(1, 2, “chocolate”, “cake”);

Another cool thing that you can do to an array is change every element in the array with the map function. This sorta works a bit like Select in C#, and can be used as follows:

fruit = fruit.map(function (i) { return i.toUpperCase();});

Here we’re going through every element in the array and then capitalizing it. Easy stuff.

If you wanted to go through every element in the array and only return elements that match certain values, you can use the filter function. So, let’s return every element that begins with ‘a’.

fruit = fruit.filter( function(i) { return i[0] === “a”; });

If you wanted to see if all the elements in your array met a certain criteria, you can use “every” function. This returns a boolean value that tells you if the entirity of the array met the criteria or not.

log(fruit.every(function (i) { return i[0] = “a”;})

Here, we’re determining if every element begins with an ‘a’. If it doesn’t, fruit.every will return a “false” value.

log(fruit.some(function (i) { return i[0] = “a”;})

This is like above, but it returns true if some element in the array meet that criteria. And finally, there is the forEach function. This basically works like a for-loop. So, suppose you wanted to loop through your array and say what fruit you’ve got in it? Easy.

fruit.forEach(function (i) { log(i); });

The next thing I’m going to talk about is functions. Functions are basically re-usable snippets of code. You create them, and then you define the tasks that each function will perform. And then you call them when you need them. Easy really. And it allows you to write cleaner code, as you’re not writing different pieces of code to do the same thing.

So, functions are really easy to make. Suppose you want to write a function that will log “Hello Mum” whenever it’s called? Well, first you’d tell the Javascript interpreter that you’re creating a function. To do that, you’ll type “function”. Then you’ll give it a name; The more descriptive the better. Ideally one that’s in camel case (all words
concatenated with the first letter of each word uppercase”. Then, in parentheses you tell it if you’re going to be passing it a parameter. Then you create some curly braces where you’re going to store your instructions and in between those curly braces, you’ll tell the interpreter what you want to do with this function. So, let’s bring that all
together and create a function.

function HelloMum (){
log(“Hello Mum”);
}

Simple, right? Now, let’s talk about scope. Examine this code:

var x = 10;

function AddX () {
var y = x + x;
return y;
}

What do you think will happen here? Well, it’ll basically return “undefined” because the function cannot access a variable that’s not within the function itself or hasn’t been passed to the function as a parameter. If you wanted to have the function access ‘x’, you’ll need to put it between those parentheses in the function declaration.

Finally, I’m going to talk about bringing this all together and writing Javascript in an object oriented fashion. So, what is Object Oriented Programming? It’s a way of structuring code that allows for readability and reusability, whilst organizing functions based upon the type of tasks they do. It’s a complicated concept that’s hard to explain, and different programming languages do object oriented programming in different ways. Some use classes (Java, C++, C#, Ruby) whilst others use prototypes. Javascript is an example of a language that uses prototypes to create objects.

With that said, let’s create an object.

var dog = {};

Now, it looks a bit like an array, but instead of using square brackets, we’ve used curly braces. Now, let’s assign some variables and functions to our dog object. You can do either do this inside or outside of the object definition. You can use:
var dog = {};
dog.name = “Red Dog”;
dog.kind = “Kelpie”;
dog.from = “Australia”;
dog.bark = function () { log(“woof”); };

There’s another way to define an object in Javascript. It’s using something called “Object Notation” and here you’re defining your object variables and functions within the curly braces.

var dog = {
name : “Red Dog”,
kind : “Kelpie”,
from : “Australia”,
bark : function() { log(“woof”);}
}

You’ll notice that the variable names aren’t instantiated with the var keyword, and that each thing in the object declaration is delimited by a comma.

And that concludes this blog post. Any questions, comments or feedback, leave it in the box below.

About Matthew Hughes

Matthew Hughes is a software developer, student and freelance writer from Liverpool, England. He is seldom found without a cup of strong black coffee in his hand and absolutely adores his Macbook Pro and his camera. You should follow him at @matthewhughes.

1 comment

  1. Great post Matthew! I have learned a lot from your posts over here. Thanks for this! I have worked with JavaScript a lot and still learning quite a few things to this day 🙂 I am always learning new things about this language, especially with packages like Jquery etc.

    Once slight thing I noticed is that in your var x = 10 example, you indicate that the function will return ‘undefined’. However, testing in Chrome it works for me. Were you trying to say if x was not declared BEFORE the function AddX() the function will return ‘undefined’?

    From my understanding, JavaScript reads a variable that was defined outside of the function as long as the variable was declared PRIOR to being used. The ‘undefined’ error only happens if a var (the value) is truly undefined or it is used before being declared. I tested your example in Chrome and it works for me. Please consider the below:

    var x = 10;
    function AddX() {
    var y = x + x;
    return y;
    }
    alert(AddX());

    Not trying to bash your post or example, just trying to make sense out of the example. Thanks.

Leave a Reply