CIT041J Index > Lecture Notes 1 - Part 1

CIT041J Lecture Notes 1 - Part 1

What is JavaScript?

JavaScript is a programming language that lives inside your Web pages, and lets you control nearly every aspect of the pages.

JavaScript is not Java
Java is not JavaScript

JavaScriptJava
Mostly lives inside a Web page1 Can build stand-alone applications
or live in a Web page as an applet.
Doesn’t need a compiler Requires a compiler
Knows all about your page Applets are dimly aware of your Web page.
UntypedStrongly typed
Somewhat object-orientedObject-oriented

So, if they aren’t the same, why do they share a name? Marketing. JavaScript was originally called LiveScript (which, in my opinion, would have been a great name: a scripting language that makes your pages come alive). Unfortunately, in 1995, when LiveScript was developed, Java was quite the buzzword, so the marketing folks decided to name it JavaScript, causing immense confusion ever since.

XHTML

All the Web pages that we build for this course will be written in XHTML. This is just plain old HTML, written according to the rulebook of XML. Here are the rules. If we write our Web pages according to these rules and the rules of HTML, they will be valid; this will become important later. Most of the time, we will use HTML and XHTML interchangeably; we’ll refer to that as (X)HTML. When we talk about something that is purely XHTML or purely HTML, we will use those specific abbreviations.

Putting JavaScript Into a Web Page

You put JavaScript into your pages between an opening <script> and </script> tag.

<script type="text/javascript">
</script>

In modern browsers, HTML5 presumes that any <script> will be JavaScript, so you can leave off the type attribute.

Protecting the Script

Once you enter the content of the <script>, you are no longer in the world of (X)HTML; you are in the world of JavaScript. If you are writing your HTML5 in XHTML format, the problem is that a validator doesn’t know this; all it sees is one big (X)HTML document, and the < and & characters are still “special.” In order to tell a validator not to treat them as special, we do this:

<script type="text/javascript">
// <![CDATA[
	// Your JavaScript goes here
// ]]>
</script>

Lines inside a script that begin with // are JavaScript comments, which JavaScript ignores. The <![CDATA[ marks the beginning of a section of your document where (X)HTML validators treat less than signs and ampersands as ordinary characters. The ]]> marks the end of the section; after that, less than and ampersand are special again. Conveniently, this is just in time for the closing </script> tag.

Be aware that this is a special case; most of the time you will not be writing in XHTML form, so you can leave off the // <![CDATA[ and //]]>.

A Real Script

Let’s actually put something into a script, and insert it into a Web page to see how it works.

<script type="text/javascript">
	alert("This is JavaScript.");
	console.log("This goes to the console.");
</script>

The word alert is a built-in JavaScript function which takes one argument. alert( ) produces a dialog box with the argument as its message.

Notice that the statement ends with a semicolon. Unlike other languages, the semicolon is not required as long as the statement is the only one on a line. If you put more than one statement on a line, you must use a semicolon to separate the statements. Here’s a “gotcha”—if you want to break a long statement across two lines, make sure you break it at a point where the first line is not a complete JavaScript statement. Otherwise, JavaScript will presume you have two different statements. In the interest of consistency, all of our examples will have semicolons at the end of each statement.

The second statement sends the string argument to the console. You can see it if you open up the developer tools in your browser (in Firefox, it’s called Web Console). You will probably want to use the console in preference to alert() as it is less obtrusive.

JavaScript is executed as soon as it is encountered in the page. If you put the preceding script into the following page at the two places that are marked, you will see this effect. If the script is in the <head> you’ll see the dialog box before the text appears on the page. [This is really lousy user interface, by the way.] If it’s in the <body>, you’ll see it after the first paragraph appears and before the second one appears.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>CIT041J at EVC</title>
<!-- put the script here first -->
</head>

<body>
<p>Paragraph one</p>

<!-- put the script here for the second test -->

<p>Paragraph two</p>

</body>
</html>

Data Types

In the previous example, the alert() and console.log() functions took a string as their argument. Strings are one of the built-in data types in JavaScript.

Numbers and Arithmetic Operations

Numbers may be integers (without a decimal point) or floating point (with a decimal point). You have all the standard numeric operations that you would find in the C and C++ programming languages: +, -, *, /, and %. The precedence is the same as you have learned. Parentheses are evaluated first; followed by multiplication, division, and mod; followed by addition and subtraction.

JavaScript gives you as much precision as possible; dividing two integers will give a floating point result. Thus, 12/5 comes out to 2.4, not 2 as it would in C or C++.

JavaScript also provides the ++ and -- autoincrement and autodecrement operators, which work exactly as they do in C and C++. A quick review:

This...Means
a++;
++a;
a = a + 1;
x = a++; x = a;
a = a + 1;
x = ++a; a = a + 1;
x = a;
This...Means
a--;
--a;
a = a - 1;
x = a--; x = a;
a = a - 1;
x = --a; a = a - 1;
x = a;

The +, -, *, /, and % operators have a shorthand form:

Thisis the same as this
x = x + 3; x += 3;
y = y - 5; y -= 5;
m = m * n; m *= n;
z = z / (3 + a); z /= (3 + a);
h = h % 12; h %= 12;

Variables

Hey! We just used some variables there, without even declaring them. Technically, that’s OK. As soon as you mention a variable in JavaScript, it springs into existence as a global variable, which is available to all functions in the document. In terms of good programming practice, this is not OK. Always declare your variables before you use them. The variables used in the preceding example about shortcuts could have been declared as:

var x;
var y;
var m, n, z; // you can declare several at once
var h = 3; // you can declare and assign at one go

JavaScript variable names are case-sensitive! This means that quantity, Quantity, QUANTITY, and QuAnTiTy are all different variables! Variable names must begin with a letter, and must be followed only by letters, digits, and underscores. Variable names are limited to 255 characters in length. If you get anywhere near this limit, seek counseling at once. If you have a variable name that consists of two or more words (such as quantityPurchased), it is conventional to capitalize the first letter of every word except the first one. [This style is known as intercaps style.]

JavaScript is untyped. That means that you don’t have to say, “this variable can only contain integers; this one contains only floating point, and that one over there contains only characters”—any variable can hold any type of data at any time. A var is a generic holder of information of any data type.

Back to data types...

Strings

In addition to numbers (integer and floating point), variables can hold string data. A string is delimited by either single or double quotes:

var str;
str = "This is a string.";
str = 'So is this one.';
str = "Isn't it great to have both kinds of quotes?";
str = 'For "situations" like this.';

If you need a string that contains both double and single quotes, you use a backslash to “protect” (or escape) the quotes that should be part of the string:

var str;
str = "Mrs. O'Hara said \"Hello\" to us.";

Other useful escape sequences are \t for a TAB, \n for a newline character, and \\ for a backslash. You may also produce an arbitrary single-byte character with the sequence \xnn; for example, the character ó has the hexadecimal code f3; so the string acción would be written as "acci\xf3n". You may also include arbitarray Unicode symbols in the form \unnnn.

String Operations

Later in the course, you will learn a large number of functions for manipulation string. There is only one string operator; the + (plus sign), which is used to concatentate strings.

var str;
var firstName;

str = "door" + "bell"; // same as
str = "doorbell"; // a silly example

// read value of firstNamne from user information

str = "Hello, " + firstName + ".";

Numbers vs. Strings

The plus sign is the only operator that is designed to work with both strings and numbers. When you “add” a string and a number, the number gets promoted to a string, and the strings are concatenated. With all other arithmetic operations, the string is converted to a number:

ExpressionEvaluates to
3 + 47
"3" + "4""34"
3 + "4""34"
"12" / 62
"12" - "6"6

Whenever you read user input (such as from a form or a dialog box) it comes in as a string. If you are going to use the input in a numeric context, you must convert that string to a number, or else the “addition effect” may give you unexpected results.

Boolean Data

Boolean data has two values; true and false. These values are usually the result of some boolean operation such as less-than, equal-to, etc. Any value that works out to zero, the null string, the null value, or an undefined variable is considered false; everything else is true. You’ll mostly use these values in conjunction with if and while, statemenets.

Arrays

When you have an array remember that array indices start at zero, not one. Also, arrays expand as they are used. In the following code, elements with indices 5 through 9 will have the null value.

var data = [ "a", "b", "c", "d", "e"];
data[10] = "x";

Decisions, Loops, and Functions

In many reference books, you will see that when there is an if, for, or while followed by exactly one statement, the book doesn’t use curly braces. We strongly recommend that you put in curly braces no matter what. First, your code is more consistent. Second, even if you have only one statement in the action part of the if or loop, you’d have to put in the curly braces if you ever added to that code. You may as well do it sooner than later.


1 It is now possible to write server applications in JavaScript using Node.js, but that is far beyond the scope of this course.