JavaScript Core
JavaScript Core
JavaScript:
A Crash Course
Part I: Core Language Syntax
Originals of Slides and Source Code for Examples:
[Link]
Customized Java EE Training: [Link]
Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Java 5 or 6, etc. Spring/Hibernate coming soon.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Intro
Firebug
• Tutorial assumes you have Firebug
– Firefox environment for executing and debugging JavaScript,
tracing Ajax HTTP calls, exploring DOM, viewing CSS, and more
– Indispensible Ajax and JavaScript tool
• Quick summary
– Download from [Link]
– Invoke with F12
– Disable by default
• Right click on green Firebug arrow at bottom right
• Choose "Disable Firebug"
• Right click on Firebug icon again
• Choose "Allowed Sites"
• Enter localhost plus your main deployment sites
• On any site, you can still hit F12 and enable Firebug on that site
(temporarily or permanently)
• For more details
– See "Ajax Development Tools" in [Link] Ajax tutorial
7 Java EE training: [Link]
References
• Books
– JavaScript the Definitive Guide by David Flanagan
– Pro JavaScript Techniques by John Resig
• Online References
– JavaScript tutorial
• [Link]
– JavaScript API references (all builtin objects)
• [Link]
• [Link]
• [Link]
• [Link]
– HTML DOM reference (with JavaScript Examples)
• [Link]
– Official ECMAScript specification
• [Link]
[Link]
8 Java EE training: [Link]
Embedding
JavaScript in HTML
Loading Scripts
• script with src
• <script src="[Link]" type="text/javascript"></script>
– Purpose
• To define functions, objects, and variables.
• Functions will later be triggered by buttons, other user
events, inline script tags with body content, etc.
• script with body content
• <script type="text/javascript">JavaScript code</script>
– Purpose
• To directly invoke code that will run as page loads
– E.g., to output HTML content built by JavaScript
• Don't use this approach for defining functions or for doing
things that could be done in external files.
– Slower (no browser caching) and less reusable
11 Java EE training: [Link]
Example ([Link])
function getMessage() {
var amount = [Link]([Link]() * 100000);
var message =
"You won $" + amount + "!\n" +
"To collect your winnings, send your credit card\n" +
"and bank details to oil-minister@[Link].";
return(message);
"alert" pops up dialog box
}
function showWinnings1() {
alert(getMessage());
} "[Link]" inserts text into page at current location
function showWinnings2() {
[Link]("<h1><blink>" + getMessage() +
"</blink></h1>");
}
12 Java EE training: [Link]
Example ([Link])
<!DOCTYPE ...><html xmlns="[Link]
<head><title>Loading Scripts</title>
...
Loads script from previous page
<script src="./scripts/[Link]"
type="text/javascript"></script>
</head>
<body>
Calls showWinnings1 when user presses
... button. Puts result in dialog box.
<input type="button" value="How Much Did You Win?"
> ...
<script type="text/javascript">showWinnings2()</script>
...
</body></html> Calls showWinnings2 when page is loaded in
browser. Puts result at this location in page.
Basic Syntax
Variables
• Introduce with "var"
– For global variables (!) and local variables.
– No "var" for function arguments
• You do not declare types
– Some people say JavaScript is "untyped" language, but
really it is "dynamically typed" language
– JavaScript is very liberal about converting types
• There are only two scopes
– Global scope
• Be very careful with this when using Ajax. Can cause race
conditions.
– Function (lexical) scope
17
– There is not block scope as in Java
Java EE training: [Link]
Operators and Statements
• Almost same set of operators as Java
– + (addition and String concatenation), -, *, /
– &&, ||, ++, --, etc
– The == comparison is more akin to Java's "equals"
– The === operator (less used) is like Java's ==
• Statements
– Semicolons are technically optional
• But highly recommended
– Consider
• return x
• return
x
• They are not identical! The second one returns, then evaluates
x. Act as though semicolons are required as in Java.
• Comments
– Same as in Java (/* ... */ and // ...)
18 Java EE training: [Link]
Arrays Example
function arrayLoops() {
var names =
["Joe", "Jane",
"John", "Juan"];
printArray1(names);
printArray2(names);
[Link] = 10;
printArray1(names);
printArray2(names);
}
function printArray1(array) {
for(var i=0; i<[Link]; i++) {
[Link]("[printArray1] array[%o] is %o", i, array[i]);
}
}
[Link] is a printf-like way to print output in Firebug
function printArray2(array) { Console window. For testing/debugging only.
for(var i in array) {
[Link]("[printArray2] array[%o] is %o", i, array[i]);
} Direct call for interactive testing in Firebug console.
} (Cut/paste all code into console command line.)
23 arrayLoops();
Java EE training: [Link]
The Math Class
• Almost identical to Java
– Like Java, static methods ([Link], [Link], etc.)
– Like Java, logs are base e, trig functions are in radians
• Functions
– [Link], [Link], [Link], [Link], Math.atan2,
[Link], [Link], [Link], [Link], [Link],
[Link], [Link], [Link], [Link],
[Link], [Link], [Link], [Link]
• Constants
– Math.E, Math.LN10, Math.LN2, Math.LOG10E,
[Link], Math.SQRT1_2, Math.SQRT2
Strings and
Regular Expressions
Functions
function triple(x) {
return(x * 3);
}
function nineTimes(x) {
return(x * 9);
}
Function as argument.
function operate(f) {
var nums = [1, 2, 3];
for(var i=0; i<[Link]; i++) {
var num = nums[i];
[Link]("Operation on %o is %o.",
num, f(num));
}
}
33 Java EE training: [Link]
Anonymous Functions
• Anonymous functions (or closures) let you
capture local variables inside a function
– You can't do Ajax without this!
• Basic anonymous function
– operate(function(x) { return(x * 20); });
• Outputs 20, 40, 60
• The "operate" function defined on previous page
• Anonymous function with captured data
– function someFunction(args) {
var val = someCalculation(args);
return(function(moreArgs) {
doSomethingWith(val, moreArgs);
});
}
var f1 = someFunction(args1);
var f2 = someFunction(args2);
f1(args3); // Uses one copy of "val"
34
f2(args3); // Uses a different copy of "val"
Java EE training: [Link]
function operate2() {
var nums = [1, 2, 3];
var functions =
[multiplier(1/3), multiplier(3), multiplier(9)];
for(var i=0; i<[Link]; i++) {
for(var j=0; j<[Link]; j++) {
var f = functions[i];
var num = nums[j];
[Link]("Operation on %o is %o.",
num, f(num));
}
}
35 } Java EE training: [Link]
Optional Args and Varargs
• You can call any function with any number
of arguments
– If called with fewer args, extra args equal "undefined"
• You can use typeof arg == "undefined" for this
– You can also use boolean comparison if you are sure that no real
value could match (e.g., 0 and undefined both return true for !arg)
• Use comments to indicate optional args
– function foo(arg1, arg2, /* Optional */ arg3) {...}
– If called with extra args, you can use "arguments" array
• Regardless of defined variables, [Link] tells
you how many arguments were supplied, and arguments[i]
returns the designated argument
• Use comments to indicate extra args
– function bar(arg1, arg2 /* varargs */) { ... }
36 Java EE training: [Link]
Optional Arguments
function convertString(numString, /* Optional */ base) {
if (typeof base == "undefined") {
base = 10;
}
var num = parseInt(numString, base);
[Link]("%s base %o equals %o base 10.",
numString, base, num);
}
Objects
Objects: Example
(Circle Class)
function Circle(radius) {
[Link] = radius;
[Link] =
function() {
return([Link] * this. radius * [Link]);
};
}
Objects: Example
(Updated Circle Class)
function Circle(radius) {
[Link] = radius;
[Link] =
function() {
return([Link] * this. radius * [Link]);
};
}
[Link] = function(n) {
if (n <= 1) {
return(1);
} else {
return(n * [Link](n-1));
}
}
MathUtils.log10 = function(x) {
return([Link](x)/[Link](10));
}
JSON: Example
var person =
{ 'firstName': 'Brendan',
'lastName': 'Eich',
'bestFriend': { 'firstName': 'Chris',
'lastName': 'Wilson' },
'greeting': function() {
return("Hi, I am " + [Link] +
" " + [Link] + ".");
}
};
Wrapup
Questions?