Introduction to JavaScript Fall 2010 Class 2

esse quam videri
Revision as of 22:55, 21 September 2010 by Matthew.ephraim (talk | contribs) (Today's Interesting JavaScript Site)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Back to Introduction to JavaScript Fall 2010

Introduction

This week, I'll be covering the most basic aspects of JavaScript. In short, this is what you'll need to get up and running. If you have any experience with JavaScript, you are probably already familiar with most of what I'm going to cover this week. However, I think there are some bad practices that get propagated by many (let's say most) JavaScript introductions. I'll talk about not only what you should do, but also what you shouldn't do when writing JavaScript.

Browser Based JavaScript

The first thing I want to make note of is that this class will focus on JavaScript being run in the browser. This is probably the only type of JavaScript that most people have been exposed to. However, there are a significant number of other applications for JavaScript that do not rely on running in the browser. We probably won't get into those applications in this introductory class, but many of the concepts learned in this class will apply to both browser based and non-browser based JavaScript.

Including your JavaScript

The first thing that you need to do when writing JavaScript for the browser is include the script on your webpage. As you may already know, JavaScript is included on the page using the <script> tag. Unfortunately, it's not quite as simple as that. There are several ways of using the <script> tag and some ways have advantages over others.

A Basic Script Tag

Let's start with a basic script tag:

  <script type=”text/javascript”>
     // your code here
     alert(‘hello’);
  </script>

Nothing too complicated. The code section opens with a <script> tag and closes with a </script>, and your code goes between the opening and closing tags. An important thing to note: the type attribute of your script tag needs to be set to text/javascript. You may notice that some browsers let you get away with not adding this attribute. Until HTML5 is more widely supported, don’t count on this being the case. Always include the type attribute.

But what if you wanted to include another file that contains your JavaScript? To do this, you simply add the src attribute and set it to the name of the file that you want to include:

  <script type=“text/javascript” src=“hello.js”>
  </script>

The code for your page is no longer between the opening and closing script tags. Instead it's in the file hello.js, which contains just the code for your page:

  // your code here

  alert(‘hello’);

This last method, including the JavaScript from an external file, is the method that will use in class.

Placing the Script Tag

So now you have a <script> tag. But where does it go?

Technically, the <script> tag can go anywhere in the head or the body of your page. All of these techniques will work:

At the top of the body

   <html>
   <head>
   </head>
   <body>
     <script></script>
     <p>some content</p>
   </body>

Or at the bottom of the body

  <html>
  <head>
  </head>
  <body>
    <script></script>
    <p>some content</p>
  </body>

Or in the head of your document

  <html>
  <head>
     <script></script>
  </head>
  <body>
    <p>some content</p>
  </body>

You may see people recommend putting the script tag at the bottom of the body. There's a good reason for this, and I will explain it later in the class.

The last method, putting the tag in the head for the page is the one we will use for class

How NOT to Include JavaScript

There are also ways to add JavaScript that technically work, but are not recommended. Adding JavaScript using these techniques will be unacceptable for this class. Below, I have listed some of those techniques:

Inline JavaScript Handlers

  <a onclick=“doSomething()”>Bad</a>
  <img onmouseover=“hover()” onmouseout=“unhover()” />
  <a onclick=“MM_badJavaScript(true)“>Bad</a>

Abusing Anchor Tags

 <a href=“javascript:void(0)”>Bad</a>
 <a href=“#” onclick=“doSomething(); return false;”>

I want to repeat what I said before: adding JavaScript using these techniques will be unacceptable for this class.

Progressive Enhancement and Unobtrusive JavaScript

In the sections above, I may have sounded somewhat opinionated about the right and wrong ways to include JavaScript. In truth, some of it is opinion. After all, if the JavaScript works like you wanted, who's to say that you did it the wrong way?

Web development, like any profession, has it's own best practices that have developed over time. In the bad old days of the web, people where somewhat careless about how they organized their web pages. This often led to pages that were hard to maintain in the long run. Often, these pages worked great under the best of circumstances, but once one thing went wrong they fell completely apart.

To help combat these types of sites, web experts decided that pages should start out with a core of solid functionality, with the fancy things added on top to enhance the user epxerience. In a nutshell, this idea is known as progressive enhancement. The following series of articles from the (fantastic) web development magazine A List Apart summarize the concepts, and hopefully give you an idea of why this class will follow the rules that it does.

Progressive Enhancement Articles

Intro to JavaScript Syntax

There are few fundamental pieces of JavaScript syntax that I want to make sure everyone understands before moving forward with the class. These parts are some of the commonly misunderstood or ignored parts of the JavaScript language. To be a truly great JavaScript coder, you must use the syntax elements correctly.

The var Keyword

The JavaScript keyword var stands for variable. Variables are a fundamental aspect of almost any programming language. Variables let you take a value and give it a special name that you can reuse throughout the program, instead of having to use the original value.

Maybe, I have a result of a math calculation that I want to hold on to

  var result = 42 + 567 / 99 + 40;

result holds on to the result of the calculation so that I can use it later.

Notice that I put var before the name of the variable. In an ideal world, I would be required to use the world var. However, JavaScript is perfectly happy to let me do this:

  result =  42 + 567 / 99 + 40;

While this technically works, it doesn't mean exactly the same thing as the version with the var keyword. This time result is "global" variable. Meaning that it's available throughout my entire program. This means that I can never predictably use a variable called result again, because result in one area of the code might clash with the other result variable and cause strange errors.

There are ways around this issue. Always using the var keyword is the first step. The rest of the steps will become more obvious when we start to talk about functions.

; (aka, the Semicolon)

In JavaScript, much like the English language, the semicolon is often ignored. Unlike English, however, ignoring the semicolon can cause serious problems.

Take this piece of code for example:

  // Some info about John;
  var firstName = “John”;
  var lastName = “Lennon”;
  // Some info about the band
  var band = “Beatles”;

It's some fairly simple code, and it uses a semicolon at the end of each line to separate statements. Technically, the code could have been written this way, without the semicolons:

  // Some info about John;
  var firstName = “John”
  var lastName = “Lennon”
  // Some info about the band
  var band = “Beatles”

Odds are, the code would still work. So what's the problem?

One potential problem has to do with how JavaScript statements are separated. In this case, each statement is on its own line. When you move to a new line, JavaScript usually considers this to be a new statement. So, without a semicolon, the code still works. JavaScript knows that you meant to move to a new line. But, with a large amount of code, these extra lines (not to mention extra comments) can take up a lot of space, which amounts to longer download times for the user.

One solution to this problem with large amounts of code is to "pack" or "minify" the JavaScript. When you pack your JavaScript, you use a special tool that will compact the JavaScript, removing comments, extra whitespace and line breaks. The programmer will still use the original code with the formatting that's optimized for humans, but the final code will be packed before it's sent to the user, which can speed up download times.

Let's pack the simple code from above:

  var v1=“;John”;var v2=“Lennon”;var v3=“Beatles”;

No more comments, and a minimal amount of whitespace. The code still works though, because the semicolons separate the statements.

But what if the semicolons are removed:

  var v1=“John”var v2=“Lennon”var v3=“Beatles”

As far as the JavaScript interpreter is concerned, this is gibberish. It will simply cause an error when it loads. If the original code is significantly complex, adding in the necessary semicolons may be somewhat of large task.

Packing is not the only reason to add in semicolons, but it's an example where leaving them off can cause confusion and limit the flexibility of your code.

Comments

Comments are one piece of JavaScript syntax that are 100% meant for humans. You could write thousands of lines of JavaScript and never once write a comment. The code would work fine. Despite this, comments will be a required part of this class.

Many programmers will say that you should use clear variable and function names in your code. By doing that, you will eliminate the need for comments. To a certain extent, this is true. Excessive commenting can often indicate that your code is hard to understand and badly organized. However, there are cases where comments can still provide value, even to very well written programs.

Good comments are meant to clarify and describe “intent”. That is, they should describe overall ideas about the code and communicate what the programmer intended to do with the code. The comments could be for particular parts of some code or they could be part of the documentation for the overall program.

Below is an example of a comment that clarifies the intent of a function. It uses // to indicate that everything else on the line is a comment and should not be read as JavaScript code:

  // Use makeCookies to bake a custom
  // amount of cookies. The maximum
  // number of cookies is 20.
  // Our cookie sheet becomes
  // overloaded after 20 cookies.
  function bakeCookies(numberOfCookies) {
     ... some code
  }

This function bakes some cookies. Another programmer could probably read through the code and figure out that the function limits the number of cookies to only 20. But, it's difficult to communicate why that limit is in place using only code. A comment can provide some extra information about the function that may be valuable to other programmers.

Sometimes, a good comment at the beginning of a library or somewhere else in the code can provide some context, or some overall information about the code that follows. The following example uses the block comment syntax. Block comments can be on multiple lines. They begin with "/*" and end with "*/". Anything else between will be considered comments:

  /*
    This library will give you some
    really nifty JavaScript effects.
    The following functions are
    available inside this library.
    ...
  */

This block comment might go on to describe some of the functions inside of the library and how other programmers might use them.

For this class, I simply ask you to clarify your code. Make sure you name your functions and variables clearly, but when something might be clearer with a comment, be sure to add one. It’s a balance, and I don’t expect anyone to have it perfect at the beginning (or the end of the class). When in doubt, add the comment. I will be sure to let you know if I think you are using too many comments (or too few).

Primitive Types

Every value in JavaScript has an associated “type”, which indicates what value can be used and determines the value’s behavior. JavaScript’s “primitive” types are the simplest, most basic types. Rather than reiterate the basic information about each primitive type, I recommend reading Wikipedia's summary of JavaScript's primitive types. The types that I didn't discuss in the lecture this week will be covered in a future class.

Today's Interesting JavaScript Site

Google's Chrome Experiments / Chrome Showcase

Since its introduction, Google Chrome has always been on the cutting edge of web standards and HTML5. This site is intended to show off what Google Chrome is capable of.

Activities

Activity 1

Getting started with Firebug

  • 1. Install Firebug
  • 2. Click on the little bug that appears in the bottom right corner
  • 3. Go to the CSS Zen Garden
  • 4. Use Firebug to explore the page. Notice that you can select elements, see their HTML and the HTML rules applied to them. You can also change the HTML and the CSS.
  • 5. You can also use Firebug to help figure out what's wrong with your JavaScript. I will show you some examples in class.

More info: A Google tutorial on using Firebug

Activity 2

Let's create a very basic page with some JavaScript

  • 1. Create a folder for the page called page (or whatever you want to call it)
  • 2. Create a new document called content.html
  • 3. Add the following code to content.html and save it:
  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  <html>
  <head>
  </head>
  <body>
  </body>
  </html>

Note: make sure that there is no whitespace beforethe DOCTYPE declaration. You would be surprised (or maybe you wouldn't be) how many problems develop if you forget this rule.

  • 4. Create a new folder inside of page called javascripts
  • 5. Inside of that folder create a new file called behavior.js and add the following to it:
 alert('test');
  • 6. Using the technique that was recommended for this class. Include the JavaScript file on in your page. Note that you can get to your JavaSript file by referencing it as "javascripts/behavior.js".
  • 7. Open content.html with Firefox. If you have included your script correctly, you should get an alert message that says "test".

This week's assignment

There isn't a formal programming assignment for this week. I just want you to read the 3 articles that are listed under the Progressive Enhancement section. Pay particularly close attention to "Progressive Enhancement with JavaScript". Be ready to discuss the articles during next week's class.