O'Reilly logo

Head First JavaScript Programming by Elisabeth Robson, Eric T. Freeman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 1. Getting your feet wet

A Quick Dip into Javascript

image with no caption

JavaScript gives you superpowers. The true programming language of the web, JavaScript lets you add behavior to your web pages. No more dry, boring, static pages that just sit there looking at you—with JavaScript you’re going to be able to reach out and touch your users, react to interesting events, grab data from the web to use in your pages, draw graphics right in your web pages and a lot more. And once you know JavaScript you’ll also be in a position to create totally new behaviors for your users.

You’ll be in good company too, JavaScript’s not only one of the most popular programming languages, it’s also supported in all modern (and most ancient) browsers; JavaScript’s even branching out and being embedded in a lot of environments outside the browser. More on that later; for now, let’s get started!

The way JavaScript works

If you’re used to creating structure, content, layout and style in your web pages, isn’t it time to add a little behavior as well? These days, there’s no need for the page to just sit there. Great pages should be dynamic, interactive, and they should work with your users in new ways. That’s where JavaScript comes in. Let’s start by taking a look at how JavaScript fits into the web page ecosystem:

image with no caption

How you’re going to write JavaScript

JavaScript is fairly unique in the programming world. With your typical programming language you have to write it, compile it, link it and deploy it. JavaScript is much more fluid and flexible. With JavaScript all you need to do is write JavaScript right into your page, and then load it into a browser. From there, the browser will happily begin executing your code. Let’s take a closer look at how this works:

image with no caption

How to get JavaScript into your page

First things first. You can’t get very far with JavaScript if you don’t know how to get it into a page. So, how do you do that? Using the <script> element of course!

Let’s take a boring old, garden-variety web page and add some dynamic behavior using a <script> element. Now, at this point, don’t worry too much about the details of what we’re putting into the <script> element—your goal right now is to get some JavaScript working.

image with no caption

A little test drive

Go ahead and type this page into a file named “behavior.html”. Drag the file to your browser (or use File > Open) to load it. What does it do? Hint, you’ll need to wait five seconds to find out.

image with no caption

Relax

Just relax. At this point we don’t expect you to read JavaScript like you grew up with it. In fact, all we want you to do right now is get a feel for what JavaScript looks like.

That said, you’re not totally off the hook because we need to get your brain revved up and working. Remember that code on the previous page? Let’s just walk through it to get a feel for what it might do:

image with no caption

JavaScript, you’ve come a long way baby...

JavaScript 1.0

Netscape might have been before your time, but it was the first real browser company. Back in the mid-1990s browser competition was fierce, particularly with Microsoft, and so adding new, exciting features to the browser was a priority.

And towards that goal, Netscape wanted to create a scripting language that would allow anyone to add scripts to their pages. Enter LiveScript, a language developed in short order to meet that need. Now if you’ve never heard of LiveScript, that’s because this was all about the time that Sun Microsystems introduced Java, and, as a result, drove their own stock to stratospheric levels. So, why not capitalize on that success and rename LiveScript to JavaScript? After all, who cares if they don’t actually have anything to do with each other? Right?

Did we mention Microsoft? They created their own scripting language soon after Netscape did, named, um, JScript, and it was, um, quite similar to JavaScript. And so began the browser wars.

JavaScript 1.3

Between 1996 and 2000, JavaScript grew up. In fact, Netscape submitted JavaScript for standardization and ECMAScript was born. Never heard of ECMAScript? That’s okay, now you have; just know that ECMAScript serves as the standard language definition for all JavaScript implementations (in and out of the browser).

During this time developers continued struggling with JavaScript as casualties of the browser wars (because of all the differences in browsers), although the use of JavaScript became common-place in any case. And while subtle differences between JavaScript and JScript continued to give developers headaches, the two languages began to look more and more like each other over time.

JavaScript still hadn’t outgrown its reputation as an amateurish language, but that was soon to change...

JavaScript 1.8.5

Finally, JavaScript comes of age and gains the respect of professional developers! While you might say it’s all due to having a solid standard, like ECMAScript 5, which is now implemented in all modern browsers, it’s really Google that pushed JavaScript usage into the professional limelight, when in 2005 they released Google Maps and showed the world what could really be done with JavaScript to create dynamic web pages.

With all the new attention, many of the best programming language minds focused on improving JavaScript’s interpreters and made vast improvements to its runtime performance. Today, JavaScript stands with only a few changes from the early days, and despite its rushed birth into the world, is showing itself to be a powerful and expressive language.

1995

2000

2012

image with no caption

It’s True.

With HTML and CSS you can create some great looking pages. But once you know JavaScript, you can really expand on the kinds of pages you can create. So much so, in fact, you might actually start thinking of your pages as applications (or even experiences!) rather than mere pages.

Note

And usually increase the size of your paycheck too!

Now, you might be saying, “Sure, I know that. Why do you think I’m reading this book?” Well, we actually wanted to use this opportunity to have a little chat about learning JavaScript. If you already have a programming language or scripting language under your belt, then you have some idea of what lies ahead. However, if you’ve mostly been using HTML & CSS to date, you should know that there is something fundamentally different about learning a programming language.

With HTML & CSS what you’re doing is largely declarative—for instance, you’re declaring, say, that some text is a paragraph or that all elements in the “sale” class should be colored red. With JavaScript you’re adding behavior to the page, and to do that you need to describe computation. You need to be able to describe things like, “compute the user’s score by summing up all the correct answers” or “do this action ten times” or “when the user clicks on that button play the you-have-won sound” or even “go off and get my latest tweet, and put it in this page.”

To do those things you need a language that is quite different from HTML or CSS. Let’s see how...

How to make a statement

When you create HTML you usually mark up text to give it structure; to do that you add elements, attributes and values to the text:

image with no caption

CSS is a bit different. With CSS you’re writing a set of rules, where each rule selects elements in the page, and then specifies a set of styles for those elements:

image with no caption

With JavaScript you write statements. Each statement specifies a small part of a computation, and together, all the statements create the behavior of the page:

image with no caption

Variables and values

You might have noticed that JavaScript statements usually involve variables. Variables are used to store values. What kinds of values? Here are a few examples:

image with no caption

There are other values that variables can hold beyond numbers, strings and booleans, and we’ll get to those soon enough, but, no matter what a variable contains, we create all variables the same way. Let’s take a little closer look at how to declare a variable:

image with no caption

We say optionally, because if you want, you can create a variable without an initial value, and then assign it a value later. To create a variable without an initial value, just leave off the assignment part, like this:

image with no caption
image with no caption

Back away from that keyboard!

You know variables have a name, and you know they have a value.

You also know some of the things a variable can hold are numbers, strings and boolean values.

But what can you call your variables? Is any name okay? Well no, but the rules around creating variable names are simple: just follow the two rules below to create valid variable names:

  1. Start your variables with a letter, an underscore or a dollar sign.

  2. After that, use as many letters, numeric digits, underscores or dollar signs as you like.

Oh, and one more thing; we really don’t want to confuse JavaScript by using any of the built-in keywords, like var or function or false, so consider those off limits for your own variable names. We’ll get to some of these keywords and what they mean throughout the rest of the book, but here’s a list to take a quick look at:

break

delete

for

let

super

void

case

do

function

new

switch

while

catch

else

if

package

this

with

class

enum

implements

private

throw

yield

const

export

import

protected

true

 

continue

extends

in

public

try

 

debugger

false

instanceof

return

typeof

 

default

finally

interface

static

var

 
image with no caption
image with no caption

Express yourself

image with no caption

To truly express yourself in JavaScript you need expressions. Expressions evaluate to values. You’ve already seen a few in passing in our code examples. Take the expression in this statement for instance:

image with no caption

If you’ve ever taken a math class, balanced your checkbook or done your taxes, we’re sure these kinds of numeric expressions are nothing new.

There are also string expressions; here are a few:

image with no caption

We also have expressions that evaluate to true or false, otherwise known as boolean expressions. Work through each of these to see how you get true or false from them:

image with no caption

And expressions can evaluate to a few other types; we’ll get to these later in the book. For now, the important thing is to realize all these expressions evaluate to something: a value that is a number, a string or a boolean. Let’s keep moving and see what that gets you!

Note

* Of course, that is assuming the variable youKnowTheRest is “fragilisticexpialidocious”.

while (juggling) {
    keepBallsInAir();
}
image with no caption

Doing things more than once

You do a lot of things more than once:

Lather, rinse, repeat...

Wax on, wax off...

Eat candies from the bowl until they’re all gone.

Of course you’ll often need to do things in code more than once, and JavaScript gives you a few ways to repeatedly execute code in a loop: while, for, for in and forEach. Eventually, we’ll look at all these ways of looping, but let’s focus on while for now.

We just talked about expressions that evaluate to boolean values, like scoops > 0, and these kinds of expressions are the key to the while statement. Here’s how:

image with no caption

How the while loop works

Seeing as this is your first while loop, let’s trace through a round of its execution to see exactly how it works. Notice we’ve added a declaration for scoops to declare it, and initialize it to the value 5.

image with no caption

Now let’s start executing this code. First we set scoops to five.

var scoops = 5;
while (scoops > 0) {
   document.write("Another scoop!<br>");
   scoops = scoops - 1;
}
document.write("Life without ice cream isn't the same");

After that we hit the while statement. When we evaluate a while statement the first thing we do is evaluate the conditional to see if it’s true or false.

image with no caption

Because the conditional is true, we start executing the block of code. The first statement in the body writes the string “Another scoop! <br>” to the browser.

image with no caption

The next statement subtracts one from the number of scoops and then sets scoops to that new value, four.

image with no caption

That’s the last statement in the block, so we loop back up to the conditional and start over again.

image with no caption

Evaluating our conditional again, this time scoops is four. But that’s still more than zero.

image with no caption

Once again we write the string “Another scoop! <br>” to the browser.

image with no caption

The next statement subtracts one from the number of scoops and sets scoops to that new value, which is three.

image with no caption

That’s the last statement in the block, so we loop back up to the conditional and start over again.

image with no caption

Evaluating our conditional again, this time scoops is three. But that’s still more than zero.

image with no caption

Once again we write the string “Another scoop! <br>” to the browser.

image with no caption

And as you can see, this continues... each time we loop, we decrement (reduce scoops by 1), write another string to the browser, and keep going.

var scoops = 5;
while (scoops > 0) {
   document.write("Another scoop!<br>");
   scoops = scoops - 1;
}
document.write("Life without ice cream isn't the same");
image with no caption

And continues...

var scoops = 5;
while (scoops > 0) {
   document.write("Another scoop!<br>");
   scoops = scoops - 1;
}
document.write("Life without ice cream isn't the same");
image with no caption

Until the last time... this time something’s different. Scoops is zero, and so our conditional returns false. That’s it folks; we’re not going to go through the loop anymore, we’re not going to execute the block. This time, we bypass the block and execute the statement that follows it.

image with no caption
image with no caption

Now we execute the other document.write, and write the string “Life without ice cream isn’t the same”. We’re done!

image with no caption
image with no caption

Making decisions with JavaScript

You’ve just seen how you use a conditional to decide whether to continue looping in a while statement. You can also use boolean expressions to make decisions in JavaScript with the if statement. The if statement executes its code block only if a conditional test is true. Here’s an example:

image with no caption

With an if statement we can also string together multiple tests by adding on one or more else if’s, like this:

image with no caption

And, when you need to make LOTS of decisions

You can string together as many if/else statements as you need, and if you want one, even a final catch-all else, so that if all conditions fail, you can handle it. Like this:

image with no caption

Reach out and communicate with your user

We’ve been talking about making your pages more interactive, and to do that you need to be able to communicate with your user. As it turns out there are a few ways to do that, and you’ve already seen some of them. Let’s get a quick overview and then we’ll dive into these in more detail throughout the book:

image with no caption

Create an alert.

As you’ve seen, the browser gives you a quick way to alert your users through the alert function. Just call alert with a string containing your alert message, and the browser will give your user the message in a nice dialog box. A small confession though: we’ve been overusing this because it’s easy; alert really should be used only when you truly want to stop everything and let the user know something.

Note

We’re using these three methods in this chapter.

Write directly into your document.

Think of your web page as a document (that’s what the browser calls it). You can use a function document.write to write arbitrary HTML and content into your page at any point. In general, this is considered bad form, although you’ll see it used here and there. We’ve used it a bit in this chapter too because it’s an easy way to get started.

Use the console.

Every JavaScript environment also has a console that can log messages from your code. To write a message to the console’s log you use the function console.log and hand it a string that you’d like printed to the log (more details on using console log in a second). You can view console.log as a great tool for troubleshooting your code, but typically your users will never see your console log, so it’s not a very effective way to communicate with them.

Note

The console is a really handy way to help find errors in your code! If you’ve made a typing mistake, like missing a quote, JavaScript will usually give you an error in the console to help you track it down.

Directly manipulate your document.

This is the big leagues; this is the way you want to be interacting with your page and users—using JavaScript you can access your actual web page, read & change its content, and even alter its structure and style! This all happens by making use of your browser’s document object model (more on that later). As you’ll see, this is the best way to communicate with your user. But, using the document object model requires knowledge of how your page is structured and of the programming interface that is used to read and write to the page. We’ll be getting there soon enough. But first, we’ve got some more JavaScript to learn.

Note

This is what we’re working towards. When you get there you’ll be able to read, alter and manipulate your page in any number of ways.

A closer look at console.log

Let’s take a closer look at how console.log works so we can use it in this chapter to see the output from our code, and throughout the book to inspect the output of our code and debug it. Remember though, the console is not a browser feature most casual users of the web will encounter, so you won’t want to use it in the final version of your web page. Writing to the console log is typically done to troubleshoot as you develop your page. That said, it’s a great way to see what your code is doing while you’re learning the basics of JavaScript. Here’s how it works:

image with no caption

Opening the console

Every browser has a slightly different implementation of the console. And, to make things even more complicated, the way that browsers implement the console changes fairly frequently—not in a huge way, but enough so that by the time you read this, your browser’s console might look a bit different from what we’re showing here.

So, we’re going to show you how to access the console in the Chrome browser (version 25) on the Mac, and we’ll put instructions on how to access the console in all the major browsers online at http://wickedlysmart.com/hfjsconsole. Once you get the hang of the console in one browser, it’s fairly easy to figure out how to use it in other browsers too, and we encourage you to try using the console in at least two browsers so you’re familiar with them.

image with no caption

Coding a Serious JavaScript Application

Let’s put all these new JavaScript skills and console.log to good use with something practical. We need some variables, a while statement, some if statements with elses. Add a little more polish and we’ll have a super-serious business application before you know it. But, before you look at the code, think to yourself how you’d code that classic favorite, “99 bottles of beer.”

image with no caption
var word = "bottles";
var count = 99;
while (count > 0) {
    console.log(count + " " + word + " of beer on the wall");
    console.log(count + " " + word + " of beer,");
    console.log("Take one down, pass it around,");
    count = count - 1;
    if (count > 0) {
        console.log(count + " " + word + " of beer on the wall.");
    } else {
        console.log("No more " + word + " of beer on the wall.");
    }
}

Brain Power

There’s still a little flaw in our code. It runs correctly, but the output isn’t 100% perfect. See if you can find the flaw, and fix it.

image with no caption

Good point! Yes, it’s time. Before we got there we wanted to make sure you had enough JavaScript under your belt to make it interesting. That said, you already saw in the beginning of this chapter that you add JavaScript to your HTML just like you add CSS; that is, you just add it inline with the appropriate <script> tags around it.

Now, like CSS, you can also place your JavaScript in files that are external to your HTML.

Let’s first get this serious business application into a page, and then after we’ve thoroughly tested it, we’ll move the JavaScript out to an external file.

How do I add code to my page? (let me count the ways)

You already know you can add the <script> element with your JavaScript code to the <head> or <body> of your page, but there are a couple of other ways to add your code to a page. Let’s check out all the places you can put JavaScript (and why you might want to put it one place over another):

image with no caption

We’re going to have to separate you two

Going separate ways hurts, but we know we have to do it. It’s time to take your JavaScript and move it into its own file. Here’s how you do that...

  1. Open index.html and select all the code; that is, everything between the <script> tags. Your selection should look like this:

    image with no caption
  2. Now create a new file named “code.js” in your editor, and place the code into it. Then save “code.js”.

  3. Now we need to place a reference to the “code.js” file in “index.html” so that it’s retrieved and loaded when the page loads. To do that, delete the JavaScript code from “index.html”, but leave the <script> tags. Then add a src attribute to your opening <script> tag to reference “code.js”.

    image with no caption
  4. That’s it, the surgery is complete. Now you need to test it. Reload your “index.html” page and you should see exactly the same result as before. Note that by using a src=“code.js”, we’re assuming that the code file is in the same directory as the HTML file.

    image with no caption

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required