Prerequisite: 1 Introduction
this, constructor, prototype; we will come to these topics in a later lesson.“JavaScript” sounds like “Java”, and JavaScript code looks a lot like Java code. But JavaScript is not Java.
The Java programming language was designed principally by James Gosling at Sun Microsystems (now part of Oracle Corporation), and publicly released in 1995. It is, to a large extent, a “simpler, safer” derivative of the C++ programming language, which in turn is derived from the C programming language, mainly by the addition of object-oriented features.
The JavaScript programming language was designed by Brendan Eich, working at Netscape Corporation, and was included in Netscape Navigator, also in 1995. Netscape Navigator was the most popular web browser before Microsoft applied its monopoly power to illegally “persuade” computer manufacturers to feature Internet Explorer on PC desktops.
Anyway, JavaScript is close in spirit to Scheme, a (mostly) functional programming language; but apparently Eich was directed to make the syntax resemble Java’s as much as possible.
JavaScript has a reputation among (over-sophisticated?) programmers as a bad programming language, as being designed for the non-sophisticated programmer, and even the non-programmer. This reputation is reinforced by many bad examples of JavaScript code, bad JavaScript books and tutorials; but as James Crockford has discovered, there is actually a good programming language at the core, although there are certainly some bad features which we should try to avoid.
JavaScript was later standardized by Ecma International (originally “European Computer Manufacturers Association”) and officially named ECMAScript.
It was designed for use in the browser, but can also be used server-side (e.g., Node.js) and even just on the desktop for ordinary non-web computing (e.g., Google v8, Mozilla SpiderMonkey and Rhino). These desktop varieties of JavaScript can be convenient for just trying out features of the language, and I will sometimes use SpiderMonkey to demonstrate core language features. The SpiderMonkey prompt looks like this:
js>
For web graphics, of course, we’ll be using it in the browser, because the graphics APIs are tied to HTML.
Enough introduction. Let’s get started!
// single-line comment (to end of line)
/* multi-line
comment */
Scripts are included in or referenced from the <script> element, like this:
<script type="text/javascript">
// script goes here
</script>
or this, reading the script from an external URL (and you can omit the type):
<script src="file.js">
</script>
Apparently, there must be an explicit closing </script> tag; this does not work:
<script type="text/javascript" src="file.js"/>
I prefer to use the src attribute, except for very short inline scripts.
At one time, it was widely recommended to use an HTML comment around the script (the content of the script element), to hide the script from people using browsers that did not yet recognize the <script> tag:
<script type="text/javascript">
<!--
// script goes here,
// hidden from lame browsers
// -->
</script>
This is probably not much needed today (but of course, it depends on your users); I won’t be using it in this course.
Since we’ll be using HTML5 (earlier versions of HTML do not have the canvas element), I want you to know the minimum syntax for a valid HTML5 page using the English language and UTF-8 character encoding:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>HTML5 Boilerplate (replace with title text)</title>
</head>
<body>
</body>
</html>
Open this link to display it in your browser — this will be just a blank page with the title placeholder; use your browser’s “view source” (usually Control-U). This should open in a new window or tab, but if it does not, use your browser’s “go back” command: HTML5 boilerplate.
Your browser will probably let you get away with less than this, using “quirks mode,” and you can do so for just trying stuff out. But if you publish a page, it should have everything in this minimum syntax.
Script elements can be placed in either the head or the body. Usually, I place function definitions in scripts in the head, and any scripts in the body are very short, little more than calls to the functions defined in the head scripts. However, for the examples in this class, I have found it more convenient to place the scripts in the body.
The canvas, of course, along with other page content, goes in the body.
A script in the body should normally come after any elements (such as the canvas element) that it manipulates.1
document.write("<p>Hello, web!</p>")
The string written is some HTML, so it may contain tags. You don’t want to use document.write too much. There are better ways (using the DOM) to manipulate the document.
Dialogs are “pop-up” windows that interact briefly with the user. Any text they display should be plain text, not HTML, so don’t use tags here.
confirm("text") shows a confirmation dialog and returns true for “OK” or false for “Cancel”:
confirm("Do you really want to launch missiles?");
alert("text") displays an alert dialog:
alert("Your pizza is ready.");
prompt("text") displays an input dialog with OK and Cancel buttons; it returns a string or, if the input is canceled, null (but in some browsers it might return the empty string in this case):
var age_input = prompt("How old are you?");
Writing messages to the browser’s debugging console:
console.info("Message", ...) // informational message
console.log("Message", ...) // general logging message
console.warn("Message", ...) // warning message
console.error("Message", ...) // error message
You need to open the browser’s debugging console to see these messages. Support for this may be browser-dependent, but it is present in Firefox and Chromium, at least.
Caution for IE9 (and possibly other versions of Internet Explorer): It seems that if the console has not been opened, calls to console.log will halt the script with no explanation. Use F12 to open the developer tools, which includes the console. After the console has been opened, console.log seems to work even if the console is subsequently closed.
May be declared with var, or just assign a value to a variable.
var x, y, z;
var w = 10;
m = 25;
But if the variable is not explicitly declared with var, it has global scope. Therefore it is best to use var!
Identifiers (variable names) are similar to C and Java, but may also contain a $ sign, though the $ sign is not meant to be used in user-written scripts (whatever that means). They are case-sensitive; by convention, do not use capital letters.
There are three primitive types: number, string, boolean. Boolean has two values: true and false. All numbers are 64-bit floating point. A string is a Unicode sequence of 0 or more characters. Its characters can be enclosed in either single or double quotes:
"beautiful"
'blue'
Everything else is (some type of) an object.
Special values:
null (counts as false in a boolean context)undefined (a variable is not defined, does not have a value)typeof(x) returns a string which is the name of the type of x, e.g., "number", "boolean", "string", "function", "object", or "undefined".
typeof(null) ⇒ "object"typeof(undefined) ⇒ "undefined"JavaScript freely converts data types to fit the context. While this can be handy, it is also dangerous; so best to avoid it.
In context where a boolean value is required:
null is false."" and "0" are false.The usual crew from C and Java, including +, -, *, /, %, ++, --.
Boolean operators: && (and), || (or), ! (not).
Also increment operators: +=, &&=, etc.
The + operator also concatenates strings. Other data are converted to strings as needed for this purpose, i.e., as long as one of the operands is a string.
Control statements similar to C and Java:
Simple if
if (condition)
statement;Two-way if/else
if (condition)
statement;
else
statement;
Note the weird requirement of a ’;’ before the ‘else’. (???)
while statement
do/while statement
for statement
for (var init; test; incr)
statement;Blocks: As in Java, multiple statements can be combined into one syntactic statement by surrounding them with { and } braces.
var n = 10;
while (n > 0) {
console.log(n);
n--;
}switch statement with case and default clauses
There’s also the C-style conditional expression:
test ? expr1 : expr2
You can build a multi-way conditional expression2 like this (see Crockford):
test1 ? expr1 :
text2 ? expr2 :
...
expr_last==, !=, <, <=, >, >=
=== and !== test for strict equality (or strict inequality), without type conversion:
5 === "5" is false5 == "5" is true== and != test for nop-strict equality (or non-strict inequality): they convert their operands to the same type:
5 == "5" is true5 != "5" is false=== and !===).Write loops that print the integers 1 through 10 on the console log. Do this with a for loop, a while loop, and a do while loop.
Write a loop that increments by 2 to print the even integers from 2 to 20 on the console log. Use any of the three looping statements that you prefer; use all three if you feel energetic.
Write a loop that prints the integers 1 through 10 on the console log, with the word “green” after each even number and the word “red” after each odd number. Use an if statement or a conditional expression (? :). Do it both ways if you feel brave.
JavaScript outside of a web browser: