JavaScript: The Basics

JavaScript is often confused with Java. While there are numerous syntactic similarities, the two languages are otherwise fairly unrelated. Java is a powerful programming language capable of generating free-standing applications on machines that support Java (most machines today), and can be used to create desktop programs, mobile apps, and server-side scripts for web sites. JavaScript, while recently made useful on the server side by systems such as NodeJS, is traditionally a front-end/client-side scripting language that is sent to the browser and interpreted on the user's machine. What this means is that, while a PHP, ColdFusion or other back-end scripting language is processed on the server before output (typically HTML) is sent to the user's browser for page generation, JavaScript is sent to the user and then run within their machine. This not only allows for attractive and user-friendly effects within the browser, but allows the user's machine to take over a large part of the burden of interactivity, while also enabling partial updates to pages using Ajax... often a cleaner, smoother, more traffic-efficient alternative to full-page reloads. What are just a few examples of what JavaScript can do?...

  1. Enable drag-and-drop for visual organization, or key-based movement for games.
  2. Handle tabbed sections of hidden content without loading page after page.
  3. Use Ajax (make an httpRequest to another page in the site's domain) to update or retrieve server data.
  4. Manipulate the DOM (known as DHTML: Dynamic HTML) as a result of data retrieved using Ajax and/or user interaction.
Language Basics

Dialogs are pop-up boxes that browsers typically have built into them. Because they're so useful in learning JavaScript because of their ability to collect user input and display output, they're the first thing I'd like to cover. They're also very easy to implement. JavaScript has three major dialog types:

alert(x): An alert containing whatever 'x' is will be displayed. For example:

confirm(x): A similar box containing whatever 'x' is will be displayed, but it will have two options: yes and no (or ok/cancel, or other combinations, depending on the browser. Additionally, the 'confirm()' function will also return either 'true' or 'false', depending on what is clicked. We'll talk about functions and return value further below. Suffice it to say for now that this function allows you to get a yes/no answer to a particular question that you pose to the user. Check out the sample below. I've combined 'alert' and 'confirm': it alerts something, and that something is whatever the user selects for the 'confirm'. So first it displays a confirm dialog, and then after that it alerts the true/false value that was returned after the user chose yes or no:

prompt(x): This one is very similar to conirm(), except instead of asking for a yes/no decision, the pop-up box contains a text input field. Instead of returning true or false, it returns the text that you type in. Let's test it out the same way:

Don't worry if confirm() and prompt() don't make a lot of sense yet. As long as you know that you can use alert() to pop up some text, we'll be able to start doing some simple work with variables and functions, and you'll see the results of the calculations that are performed by using alerts in the examples.

Event Listening

Another useful feature of JavaScript is the use of Event Listeners. In fact, because of the nature of its use for improving the user experience in a web environment, JavaScript typically involves a lot of "event-driven programming". Because the examples that you will find throughout these tutorials rely so heavily on listening for events like button clicks and page loads, I will go ahead and introduce this concept early on. It's relatively simple. Elements on an HTML page have a variety of event listeners by default. For example, the document in the browser window, as well as the body of the page (document and document.body, respectively) both have an 'onload' event that defaults to nothing. One can easily attach a JavaScript function within the script, or directly in the HTML using an inline code properties like onclick="doSomething()" or onload="doSomething()" to invoke a function whenever that event occurs on that element. In the case of the buttons that you click in this tutorial, an onclick="runCodeBlock(some_codeblock_id)" call is made that interprets the code in the block and executes it. Here is an example of how a simple alert could be attached to a button:

Variables and Operators :: Numbers and Strings

Variables are essentially temporary value storage units. By setting a variable, you tell JavaScript that if you refer to that variable, you're referring to that value. Later you'll see that the 'value' of a variable could be something complex, like a reference to an array of items, an object with many properties, or even a function. But for now, let's look at some simple examples of declaring variables, setting values using numbers and text strings, and then performing some simple operations like math and combining strings:

/* Note how this section is formated with slashes and asterisks. This is one way to include comments about your code. The text between the opening and closing marks will not be run as JavaScript. */ var a = 1; /* Declare a variable 'a' and set its value to 1 */ var b = 2; /* Declare a variable 'b' and set its value to 2 */ var c = a + b; /* Declare a variable c, but this time, it's value is whatever we get by adding a+b */ alert(c);

Notice that our code ran when the button was clicked. This is because some code was included in the HTML that instructed the browser to go get the code, interpret it as JavaScript, and then run that script. However we haven't gotten that far yet, so let's just look at the code block above as-is. If you were to put this code in your JavaScript file (and nothing else) and run your page, then you would see the alert as soon as the page opened up. For now, that will suffice.

Numbers aren't the only thing you can store in a variable. (What fun would that be?) You can store strings, too. Strings are a collection of characters... in other words, a text. For example, "cat" is a string of the characters 'c', 'a' and 't', "strung" together into an array. In fact, when we look at arrays later (collections of values), we'll see that strings are technically considered by JavaScript to be arrays of characters. What is also important to note now is that we can start using our other dialogs to make our code a little more interesting:

var name = prompt("What is your name?"); var answer = confirm("Hello, " + name + "... Are you doing well today?"); alert("It is " + answer + " that you are feeling well today.");


We've looked at some simple variable types, including numbers and strings. Now I'd like to look at more complex variables: arrays. As I mentioned earlier, a string is actually an array of characters. You can also put other values in arrays, including entire other variables, and those variables can themselves be arrays, meaning arrays can quickly become very complex. Take the following code, for example. We'll do several more complicated things, and then take a look at each piece more closely:

/* var animals = []; */ var animals = new Array(); animals.push("Zebra"); animals.push("Horse"); animals.push("Donkey"); animals.push("Aardvark"); alert("There are " + animals.length + " animals in our array."); alert("The first element is " + animals[0]); alert("The last element is " + animals[animals.length-1]);

There are several things to note about the code above. First, take note of how a new empty array is created. In the commented-out line, I point out that you can use '[]' as shorthand for an empty array. You can also explicitly declare it as a new instance of an Array() object. It makes little difference. In future examples, I'm likely to use the shorter '[]' notation, and when we get to JSON later, this notation will become even more familiar to you.

Second, notice how I add items to the array using the ".push()" extension to the name of the variable. This invokes a method (a function) that all arrays are automatically aware of in JavaScript. We'll see how functions work, and how you can write your own, later in this tutorial. There are other ways (again, using shorthand) to build up arrays, and we'll see those in future examples, as well.

Third, note how we count the items in an array: using the ".length" extension. All arrays (including strings!) automatically have a "length" value that can be retrieved to find out how many characters or other values it contains. We can include that value within a string that we build up inside of an alert() call in order to announce how many animals our new array has once we're done building it.

Fourth, take a good look at how the alerted strings are constructed. You can add strings together in JavaScript by simply using the same '+' operator that you use for numbers. If JavaScript sees that they're strings, it'll just concatenate them into a single string.

Finally, and this is EXTREMELY important: note both (1) how we referenced the numeric index of the array to get a value at a particular position, as well as (2) how the indexes are counted. Instead of counting elements in an array starting with 1, JavaScript (like many languages) starts with 0. So the 0-item is the first one, the 1-item is the second, and so on. This is very important in the section that follows on looping. Don't worry too much about why this is the convention... just remember that it is, and trust that there are some mathematical advantages to writing the code this way instead of starting with 1.

Logic and Looping
Conditionals: if... then... else

Earlier, we saw an example involving prompting the user for their name and responding to it with a follow-up question. But that example was a bit silly: Since so far we've only looked at dialogs and simple variable setting, it's hard to do much with the little interaction above. But JavaScript has logical operators and conditional syntax that allows for us to check if certain things are true, and do things based on what we find out. The simplest way to do that is to use the if(x){...} to check if 'x' is true, and do to whatever is contained within the {...} block if so. Let's modify our code a bit:

var name = prompt("What is your name?"); var answer = confirm("Hello, " + name + "... Are you doing well today?"); if (answer) { alert("That's great!"); } else { alert("Oh, that's too bad."); }

The 'else{...}' block that immediately followed the closing bracket of the if{...} block. This else block lets you define a set of instructions to carry out if the condition above is not met. You can string together a lot of else/if blocks if you like. Let's modify our code again, and instead of asking how you are, just have the script respond different based on the name you enter:

var name = prompt("What is your name?"); if (name=="Jon") { alert("Hey, you're the author!"); } else if (name=="John") { alert("Oh, that's a nice name. I know a Jon without an 'h'."); } else { var al = "Hmm...\"" + name + "\", huh? I don't know you, but it's nice to meet you."; alert(al); }

Note that the true/false value we check in the if() clause in the earlier example was simply a single variable: 'answer'. This was because we retrieved a true/false value for that variable in the preceding line. In the example directly above, we had to use a more complex expression. We were no longer checking if the variable itself was set to true, but whether it was equal to a particular value.

Also note the use of \" for double quotes that occur within the quoted string that we're building up there. Quotes (both 'single' and "double" quotes) serve two purposes in JavaScript: (1) as actual quote characters in text, and (2) to surround strings when referring to them as values. So if you want to wrap quotes as characters within a string that you're wrapping inside of quotes, you have to 'escape' them, which is done by adding a backslash ("\") before them. This is a common way of escaping other characters. In many cases, you can just use different types of quotes to avoid having to escape anything. For example, in the second alert above, 'h' is single-quoted within a set of double quotes around a string, which is just fine and requires no escape slashes.


One of the particular useful things about arrays (instead of just a list of separate variables) is that we can use JavaScript to loop through them as a coherent set. For example, suppose you have an array of complex variables that represent the concept of individual persons, such as a list of employees. You might want to cycle through this list in a systematic way. This is possible using 'for-loop', which is demonstrated here:

/* var animals = []; */ var animals = ["Zebra","Horse","Donkey","Aardvark"]; var alertString = "There are " + animals.length + " animals in our array:"; for (var i=0 ; i < animals.length ; i++) { alertString += "\n - " + animals[i]; } alert(alertString);

Note how the array was created this time. I used the kind of shorthand that I will use more often, namely simply typing [brackets] containing a comma-separated list of items or values in they array.

The script begins by building an introductory string of text that indicates how many animals are in our array (by including the .length value, as we've seen before). It then proceeds to loop through all of the elements one by one until the entire list has been read using a 'for-loop'. For-loop syntax may seem confusing at first, but it is really quite simply and incredibly common in all kinds of programming. Let's take a look at the structure:

for ( doBefore ; doWhile ; doAfter ) { // Do this each time through }

The first piece in the parentheses (the pieces are separated by ";") is where you set an initial condition. In our case, we set i=0, because we want to start counting with the 0-item (the first one) in our array and then count on up through each thing it contains. We'll use this 'i' as the index in our array in each run through the loop.

The second piece in the parentheses is where we set the condition for continuing with the loop. The loop will only begin if this condition is met, and it will repeat as long as it continues to be true. In our case, we indicate that we want to continue in the loop as long as our index (i) is less than the length. Why less than, and not equal to? Remember that we started counting with 0. That means for any array of length N, the last element will be N-1. An array with 4 elements will have indexes 0, 1, 2 and 3, as is the case with our animals array.

The third piece in our parentheses is where we specify what should occur after each run through the loop. This is very frequently (in fact almost always) simply an incremental step up or down in the value of our index. In our case, we have used the instruction i++, which is shorthand for i=i+1. In other words, we want to start with 0, and each time we go through the loop, add one to our 'i' before going into the next cycle. So first we'll use 0, then add one and use 1, and then add 1 and use 2, and then add 1 and use 3, and then add 1 to... oops! It'll stop there, because 4 is equal to the length, and no longer less than it, which was our condition! See how that works? Instead of continuing after that, the loop will break and the script will finally continue past the loop.


While-loops are somewhat similar to for loops, in that they are used to cycle through a set of instructions until a condition is no longer met. However these loops do not contain the complexity that for-loops do. Instead, a while loop has a much simpler syntax. Let's look at an example using a prompt() dialog. The following code will cause a prompt to pop up, and it will continue to pop up until you enter the exact string 'password' (all lower case):

var x = ""; while(x != "password") { x = prompt("Password?: "); }

While-loops are somewhat similar to for loops, in that they are used to cycle through a set of instructions until a condition is no longer met. However these loops do not contain the complexity that for-loops do. Instead, a while loop has a much simpler syntax. Let's look at an example using a prompt() dialog. The following code will cause a prompt to pop up, and it will continue to pop up until you enter the exact string 'password' (all lower case):

var animals = ["Zebra","Horse","Donkey","Aardvark"]; var i = 0; var alertString = "There are " + animals.length + " animals in our array:"; while(i < animals.length) { alertString += "\n - " + animals[i]; i++; } alert(alertString);

As you can see, this while-loop version of our notification does essentially the same thing as the for-loop. It is entirely possible to completely exclude for-loops from your code, however they are so common and useful that you are likely to become very familiar with them and use them throughout. Typically, for-loops are used to iterate through a set with a known length (or at least a length that JavaScript can be aware of). On the other hand, while-loops are used for open-ended conditions when it's not really about counting through a set, but rather waiting for a particular condition to be met.

Functions and Methods
Built-in Functions

It is impossible to efficiently cover ALL (or even MOST) of the functions available to you in JavaScript in a tutorial like this. What's more important is to simply point out that such functions exist, and then tell you to go online to sites like W3 Schools and work through their tutorials and references to learn more about what is available in the language. Therefore, I will devote this section to just a few mathematical and string manipulation functions, and then move on to how you can define your own functions in the next section. Let's jump straight into some code.

In each of these examples, one thing you may notice is that you see a lot of dots! JavaScript uses this common 'dot-notation' to represent the relationship between an object and a property or method that it has. So if you have a 'ball' that can 'bounce', then you can call 'ball.bounce()' to make it do that. Similarly, if you have a 'book' that has an array of 'pages', you can refer to that array as 'book.pages'. In fact, you can string together many dots. To find out just how many books, you could refer to 'book.pages.length'. You can look at the dots as getting more specific. A book has pages, and there's a length of pages (the number of them that the book has). When we move on to the DHTML tutorial, this will be especially important, as you dive into manipulating the individual properties of the style of DOM elements.

var a = 2.7; var b = 2.1; bFloor = Math.floor(b); bCeiling = Math.ceil(b); alert( b + " rounds up to " + bCeiling + " and down to " + bFloor ); alert( Math.max(a,b) + " is the greater of " + a + " and " + b );

Another thing you may notice is that many of these functions seem to be pulled out of thin air. I mean... how does JavaScript know what 'Math.floor' means? This is simply something you'll learn as you code, looking up ways to do things along the way, and discovering what functions are built in to particular types of variables and the libraries that JavaScript has at its disposal. For example, the 'Math' library is essentially a built-in object type that contains a variety of publicly available methods such as 'ceil' (round up to the nearest integer), 'floor' (round down likewise), and 'max', which takes multiple values and returns the highest one. (There's a similar 'min' function.)

The string object type also has methods (a method is basically a function that on object is able to perform) that are immediately available to any variable that is a string. The 'split' method breaks a string up into an array of smaller strings by separating them using whatever character you pass. In our example below, we pass a blank space, so all of the separate words are slotted into an array index. Strings also have a 'replace' function, which takes one string that you want to replace, and another string that you want to replace it with. In fact, it also allows for a third (optional) parameter that we didn't need to use, which lets you include other flags such as 'g' (for "global") to indicate that it should do something (like replace all instances of the string, and not just the first it finds).

var s = "This is a string."; s = s.replace(".",""); alert("String length: " + s.length); var sArray = s.split(" "); alert("Number of words: " + sArray.length + ": " + sArray.join(" | "));

What you may have noticed by now is that some functions seem to be attached to objects, and others seem to just be floating out there loosely. For example, you can call 'alert()' without doing it from a particular object, but you have to use "Math.min" and not just "min" to get the minimum of two values. Why is this? It turns out that those free-floating functions are actually window object functions. Because the window is typically the default scope in JavaScript, free-floating functions will be assumed to be called by the window. If the function doesn't exist on the window, then it will throw an error. You can see this demonstrated below, where I've appended 'window' in front of a few of our familiar functions:

if (confirm("Do you want to see a visual echo?")) { window.alert(window.prompt("Then type something!")); }

Defining Custom Functions

We've seen quite a few string and math functions already, and of course there are many more that you can reference by going online and looking up how to do things you want to do. However another useful feature of JavaScript (as with most programming languages) is that you can declare your own functions and give JavaScript instructions on how to carry it out. What this requires is that we...

  1. Declare a name for our function.
  2. Indicate what information we will (or might) pass to it.
  3. Write a set of instructions within the brackets that the function will carry out (probably using the values you just passed in). If your function is supposed to return information, then these instructions will include a 'return' command at the end.

Let's look at a very simple example:

function customAdd(a,b) { return a + b; } alert(customAdd(1,2));

Let's look at how we implemented the requirements listed above in the example we just saw:

  1. We declared the name 'customAdd' for our function by saying 'function customAdd'.
  2. We indicated that we'll pass two variables: 'a' and 'b'.
  3. We wrote a single-line instruction, which was our return command. What we returned was the result of adding our two numbers together.

Because our function was called inside of the alert() parentheses, its return value was used as the argument in ANOTHER function, namely the alert. So what we said was "alert whatever we get when we call the customAdd function on 1 and 2".

Function Scope

It's important to understand that, inside of a function, the variables that you pass inside of the parentheses are known to the function's commands as long as you're inside that block. In fact, if you have variables by those names elsewhere in your code, it'll ignore them and use those instead. Here's an example that demonstrates this:

function scopedAdd(a,b) { var c = 1; a++; return a + b + c; } var a = 1; var b = 2; var c = scopedAdd(a,b); alert("a: " + a + "\nb: " + b + "\nc: " + c);

We original set a=1 and b=2. Inside of our function, we also used the variable names 'a' and 'b'. We also separately create variable 'c' inside of that block and set it to 1. Then we increment the 'a' we passed in by 1, which mean it should equal 2. So when we return a+b+c, we're returning 2+2+1, which is 5. This is indeed what we see, since once we set 'c' to that value and alert all three, we see '5', not '1'. This means that the value of 'c' was left untouched outside of the function, because it was separately declared using 'var' inside of our function block. Similarly, since 'a' was passed in as a variable in our parameters, which means that it was automatically considered a new and temporary 'a', and the other value was ignored. However one interesting thing about JavaScript (and this is much different in other languages) is that, if the variable is neither passed as a parameter nor explicitly declared with 'var' inside of the block, then the function assumes that it's using a global variable (yep... based on the window's variable values), and anything you do to it will change it outside of the function, too. Let's see two contrasting examples that demonstrate this:

function scopeDemo() { x++; alert("x inside the function: " + x); } var x = 1; scopeDemo(); alert("x outside the function: " + x);

function scopeDemo() { var x = 1; x++; alert("x inside the function: " + x); } var x = 1; scopeDemo(); alert("x outside the function: " + x);

This is why it's always a good idea to use 'var' before declaring a variable. In your base code, you're likely to use complex variable names like 'myBigBox', but in functions, it's often tempting to re-use single letters or more generic names like 'sum', and if you don't explicitly re-declare it using 'var' inside of your function, then. But AGAIN: don't worry about this rule if it's one of the variables that you're passing in... only if you think you're using it fresh for the first time inside your function block, and there's some chance that you might have used it somewhere else in your code.

Coming Soon: Functions as Objects

This should give you a basic idea of how to use existing window functions and object methods, however eventually you'll start looking at object-oriented programming using classes. In JavaScript, classes are declared as functions, and their methods are functions too. Functions can actually be bundled up - scope, parameters and all - and passed to other functions like you would a variable. We'll dive into that soon enough!

Recommended next: Dynamic HTML