Introduction

This series of tutorials is meant to get you familiar with Javascript so you can use it to do some cool stuff on your site. Javascript is an interpreted language that is executed client-side in a Javascript-enabled browser. Javascript is a good scripting language to use because nearly all modern browsers support it.

This first tutorial will get you started with Javascript, its most basic concepts such as variables, Strings, functions, and its integration with the DOM.

The Basics

This section will talk about the basic concepts such as variables and functions, the building blocks of any basic Javascript code, from snippets to applications.

Variables

Being an interpreted, weakly-typed language, variables are a simple concept in Javascript with some potentially complex implications if you aren't careful. Much like PHP and other similar scripting languages, variables don't need to have a type declared to them when they are created, and also much like other languages, variables can hold a reference to just about any kind of data. Take a look at the following code block to get a feel for the syntaxt


name = "James";
age = 20;
sum = 10 + 5;
greeting = "Hi, my name is " + name;

Following the above code snippet, we will see the values of our variables are as follows:

name: "James"
age: 20
sum: 15
greeting: "Hi, my name is James"

Another way to declare variables is to use the var keyword like this:

var website = "http://www.atomicpages.net";

The difference between declaring a variable with or without the var keyword has to do with a concept of "scope" which is beyond the scope (hah!) of this tutorial, but will be covered in future posts. For now, consider the difference between the two negligible.

Arrays

Arrays are a useful data structure that work very similar to and have the same uses as arrays from other programming languages. Arrays are data structures that store data at different indices indicating exactly where in the structure a particular point of data is. Imagine an array as a 2 dimensional series of boxes laid end to end with the first box being the "0th" box, the next one to the right being the 1st, then next the 2nd, and so on. There are a few ways to create arrays in Javascript depending on what exactly you want to do. The following lines of code each create an empty array, that is, an array that contains no data.


myarray = new Array();
myarray = [];

This is rather boring, however, because what good is an array if it doesn't contain any information! Look closely at the following lines of code and their subsequent explanations following the code block


myarray = new Array(4);
cats = new Array("Dusty", "Boo", "Scout");
mycats = ["Dusty", "Boo", "Scout"];

The first line of code is almost exactly the same as the first line of the previous set of examples, the only difference being the 4 within the parenthesis. This number inside the parenthesis is what is called a parameter. A parameter is something you put inside the parenthesis of a function to get a specific result based on your parameter. A common analogy is taken from mathematics where you have a function f(x) = 2x. You can put any number you want in place of the "x", and get back an answer (f(2) = 4, f(10) = 20).Functions and parameters work very similar to this. We will discuss functions in more detail in a later chapter but for now, consider the parameter 4 in the context of making an array.

After the 1st line of code executes you are left with an empty array of size 4. In the previous examples, you created completely empty arrays that didn't even have boxes to put anything in but in this example, you are saying "make a new array that is 4 boxes long".

At first glance, lines 2 and 3 look very different but in fact they do the same exact thing (except of course the variable names ["cats" and "mycats"]). In both cases, you are creating an array that is 3 boxes long where each box contains a String (the name of a cat).

One of the cool things about arrays is that is very easy to both look up and add data to it. Consider the following code:


mycats = ["Dusty", "Boo", "Scout"];
cat1 = mycats[0];
cat2 = mycats[1];
cat3 = mycats[2];
mycats[3] = "Skippy";
cat4 = mycats[3];

If this code seems a little confusing at first, that's ok, it can look like a lot is going on. In reality, what is going on here is very simple:

Recall that when dealing with arrays, the very first item is the "0th" item. That means, after this code runs, the thing stored in the cat1 variable is "Dusty". As you can probably guess then, the thing stored in the cat2 variable is "Boo", and so on.

When we get to the 4th line, you see you see that we reference the "3rd" box in the mycats array. If you've been following along, you might say to yourself, "there is no 3rd box! There are three items in the array so it only goes up to 2! (0, 1, 2, ...)". And if you're thinking this, you're exactly right, there is no "3rd" box... yet. What the 4th line is actually is saying is "stick another box at the end and push the value "Skippy" into it." Now that there is something at the 3rd index of the array, when we get to the 5th line, the variable cat4 stores, you guessed it, "Skippy"!

Putting it all to use

We've been moving pretty fast getting through the basics of Javascript but we haven't quite done anything cool with it yet, and that can be a bit frustrating. But fear not! We are finally going to do something interesting with what we have learned.

First things first, you'll want to prepare your HTML document for writing some Javascript code. Create a new HTML file and make sure it looks like this:

<html>
<head>
<script type='text/javascript'>

//enter your code here <-- this is a Javascript comment, anything after the "//" will be ignored

</script>
</head>
<body>
</body>
</html>

This is the bare minimum you'll need to run some Javascript code. We will be writing all of our code in between the tags so you can ignore all the other ones. If you're interested in learning more about HTML though, feel free to check out the HTML tutorials available on this site. (A healthy foundation of HTML can certainly improve your understanding of Javascript.)

For this code snippet, we will be displaying a variety of greetings for several users at once. Let's start by creating some variables. Add this in between the script tags (you can delete the comment if you like):

users = ["Darth Vader", "Frodo", "Count Chocula", "Sherlock"];
greeting = "Welcome to my web page, ";

Nothing to complicated going on here. As you can see we are creating a new array and putting the names of some potential visitors in it. Next, we are defining our greeting as the beginning of a welcome message. Keep in mind, we can call our variables anything we want. We could have called our greeting chocolateCake if we wanted, though if someone else wanted to look at our code, it would be very difficult for them to tell what was going through your head. It's usually best to keep variable names descriptive of what they do, both for yourself and others.

Next, add the following code beneath what we have above:

document.write(greeting + users[0] + "
");
document.write(greeting + users[1] + "
");
document.write(greeting + users[2] + "
");
document.write(greeting + users[3] + "
");

And that's it! we've written our first working snippet of Javascript code! To see it in action, bring up the HTML page in your browser (Firefox, Chrome, Internet Explorer, etc.). You should get something like this:

Welcome to my web page, Darth Vader
Welcome to my web page, Frodo
Welcome to my web page, Count Chocula
Welcome to my web page, Serlock

And there we have our first bit of Javscript code! Give yourself a pat on the back, you've just taken your first step into the wide world of Javascript. For now, just ignore the document.write() call and the "<br>" bits, the former will be covered in a future lesson and the latter is a bit of HTML that you can learn more about from the HTML tutorials.

Conclusion

We've covered a lot in this first chapter and we're on our way to building a solid foundation of understanding of Javascript. In this lesson, we touched on variables, arrays, and String concatenation (adding two strings together). This was enough for us to write a small block of code that stored the names of visitors in an array and outputted greetings to each one using the indices of the users array. I hope you enjoyed this first tutorial and that you feel like you've learned something from it. If anything is still confusing, I recommend rereading it a couple times until it sticks (go on, its not that long).

Extra Practice

In our snippet of Javascript code, try doing the following:

1. Add more users to the users array and display a greeting for them as well. (Try doing this both when the array is created and after)
2. Change the greeting to an away message: "Thanks for visiting my site, " Remember to change the name of your variable as appropriate.

Be Sociable, Share!