Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
44 views

JavaScript 1 Core Syntax

JS Core Syntax

Uploaded by

David Joseph
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views

JavaScript 1 Core Syntax

JS Core Syntax

Uploaded by

David Joseph
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

2010 Marty Hall

JavaScript:
A Crash Course

Part I: Basics and Core Language Syntax


Originals of Slides and Source Code for Examples:
http://courses.coreservlets.com/Course-Materials/ajax.html
http://courses.coreservlets.com/Course
Materials/ajax.html
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.

2010 Marty Hall

For live Ajax & GWT training, see training


courses att http://courses.coreservlets.com/.
htt //
l t
/
Taught by the author of Core Servlets and JSP,
More Servlets and JSP,
JSP and this tutorial.
tutorial Available at
public venues, or customized versions can be held
on-site at your organization.
Courses
C
d
developed
l
d and
d ttaught
ht b
by M
Marty
t H
Hallll
Java 6, servlets/JSP (intermediate and advanced), Struts, JSF 1.x, JSF 2.0, Ajax, GWT 2.0 (with GXT), custom mix of topics
Ajax courses
can concentrate
on 1EE
library
(jQuery, Prototype/Scriptaculous,
Ext-JS, Dojo, Google Closure) or survey several
Customized
Java
Training:
http://courses.coreservlets.com/

Courses developed and taught by coreservlets.com experts (edited by Marty)

Servlets, Spring,
JSP, JSF
2.0, Struts,
Ajax,
GWT
2.0,Ruby/Rails
Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Hibernate/JPA,
EJB3,
Web
Services,
Contact
hall@coreservlets.com
for details
Developed and taught by well-known
author
and developer. At public
venues or onsite at your location.

Topics in This Section

Overview
JavaScript references
Embedding in browser
HTML versions
Basic syntax
Arrays
Strings and regular expressions

2010 Marty Hall

Intro
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.

Example (loading-scripts.html)
<!DOCTYPE ...><html xmlns="http://www.w3.org/1999/xhtml">
<head><title>Loading Scripts</title>
...
Loads script from previous page
<script src="./scripts/phish.js"
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?"
onclick='showWinnings1()'/>
...
<script type="text/javascript">showWinnings2()</script>
...
</body></html>
/
/
Calls showWinnings2 when page is loaded in
browser. Puts result at this location in page.

12

Example (Results)

13

Loading Scripts: Special Cases


Internet Explorer bug
Scripts with src fail to load if you use <script.../>.
You must use <script src="..." ...></script>

XHTML: Scripts with body content


It is an error if the body of the script contains special
XML characters
h
t suchh as & or <
E.g. <script...>if (a<b) { this(); } else { that(); }</script>
So,
So use CDATA section unless body content is simple
and clearly has no special characters
<script type="text/javascript"><![CDATA[
JavaScript Code
]]></script>
14

2010 Marty Hall

HTML Versions and


p
JavaScript
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.

Summary
XHTML
Most common version used with Ajax apps or Dynamic
HTML apps (JavaScript apps that manipulate the DOM)
Follows XML syntax
syntax, lowercase tags

HTML 5 (sort of)


Growing
G
g in ppopularity
p
y for Ajax
j or DHTML apps.
pp
Version used now is basically XHTML but with a simpler
DOCTYPE and <html> start tag
Doesnt
D
t matter
tt if browser
b
really
ll supports
t HTML 5

HTML 4
Very common in non
non-JavaScript
JavaScript apps
Not recommended for Ajax apps
16

XHTML
Summary
F
Follows
ll
XML syntax. Lowercase
L
tags, endd tags required,
i d
quotes around attribute values.

Basic structure
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www
xmlns http://www.w3.org/1999/xhtml
w3 org/1999/xhtml">>
<head><title></title></head>
<body> </body></html>

Pros
Code corresponds very directly to internal (DOM)
representation by the browser

Cons
DOCTYPE and <html> start tag are long and tedious
17

Pseudo-HTML 5
Summary
F
Follows
ll
XML syntax. XHTML ((transitional)
i i l) syntax but
b
with simpler DOCTYPE and <html> start tag.

Basic structure
<!DOCTYPE html>
<html>
<head><title> </title></head>
<head><title></title></head>
<body> </body></html>

Pros
C
Code
d corresponds
d very di
directly
l to internal
i
l (DOM)
representation by the browser

Cons
Not strictly compliant with spec. May get warnings from
formal validators, especially with non-CSS formatting.
18

HTML 4
Summary
Does not follow XML syntax. Tags not case sensitive. End
tags and quotes on attribute values sometimes optional.

Basic structure
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD><TITLE> </TITLE></HEAD>
<HEAD><TITLE></TITLE></HEAD>
<BODY> </BODY></HTML>

Pros
Simple code. Widely used in non-Ajax apps.

Cons

19

S
Source code
d and
d iinternal
t
l browser
b
representation
t ti can be
b
substantially different, requiring mental translation when
thinking of how to manipulate DOM from JavaScript.

2010 Marty Hall

Basic
JavaScript
p Syntax
y
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.

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
technicallyy it is dynamically
y
y typed
yp
language
g g
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
conditions.
21

Function (lexical) scope


There is not block scope as in Java

Operators and Statements


Almost same set of operators as Java

+ (addition and String concatenation)


concatenation), -, *,
* /
&&, ||, ++, --, etc
The == comparison is more akin to Javas equals
The === operator (less used) is like Java
Javass ==

Statements
Semicolons are technically optional
But highly recommended

Consider
return x
return
x
They are not identical! The second one returns, then evaluates
x. You should act as though semicolons are required as in Java.

Comments
Same as in Java (/* ... */ and // ...)
22

Conditionals and Simple Loops


if/else
Almost identical to Java except test can be converted to
true/false instead of strict true/false
false:
false : false,
false null
null, undefined
undefined, "" (empty string),
string) 0
0, NaN
true: anything else (including the string "false")

Basic for loop


Identical to Java except for variable declarations
for(var i=0; i<someVal; i++) { doLoopBody(); }

while loop
Same as Java except test can be converted to boolean
while(someTest) { doLoopBody(); }

do/while loop
23

Same as Java except test can be converted to boolean

Other Conditionals and Loops


switch
Differs from Java in two ways
The case can be an expression
Values need not be ints (compared with ===))

for/in loop
On surface, looks similar to Java for/each loop, but
For arrays, values are array indexes, not array values
Use this loop for objects (to see property names), not arrays!
Fails with Prototype or other extended arrays

For objects, values are the property names

var person = { firstName: "Brendan", lastName: "Eich"};


for(var property in person) {
doSomethingWith(person[property]);
}
24

The Math Class


Almost identical to Java
Like Java, static methods (Math.cos, Math.random, etc.)
As we will see in next lecture, these are not really static
methods,, but syntax
y
is similar to static methods in Java.

Like Java, logs are base e, trig functions are in radians

Functions
Math.abs, Math.acos, Math.asin, Math.atan, Math.atan2,
Math.ceil, Math.cos, Math.exp, Math.floor, Math.log,
Math.max, Math.min, Math.pow, Math.random,
Math.round, Math.sin, Math.sqrt, Math.tan

Constants
Math.E, Math.LN10, Math.LN2, Math.LOG10E,
Math.PI, Math.SQRT1_2, Math.SQRT2
25

2010 Marty Hall

Arrays
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.

Array Basics
One-step array allocation
var primes = [2, 3, 5, 7, 11, 13];
var names = ["Joe", "Jane", "John", "Juan"];
No trailing comma after last element (see later slide)

Two-step array allocation


var names = new Array(4);
y( );
names[0] = "Joe";
...
names[3] = "Juan";
Juan ;

Indexed at 0 as in Java
for(var
o (va i=0;
0; i<names.length;
a es. e gt ; i++)) {
doSomethingWith(names[i]);
}
27

Looping Down Arrays in


JavaScript
Java-style for loop

Roughly same as in Java.


Java Don
Dontt forget the var!
var !
for(var i=0; i<someArray.length; i++) {
var value = someArray[i];
doSomethingWith(value);
g
(
);
}

JavaScript-specific for loop

Relies on fact that a nonexistent array


y index results in a value
off undefined
d fi d (not
(
an exception)
i ) andd that
h eundefined
d fi d means
false in a test.
for(var i=0, value; value=someArray[i]; i++) {
doSomethingWith(value);
}

for-in loop

Not recommended for looping down normal arrays.


arrays
Returns indexes, not values
Array-like objects can have extra properties

28

More on Arrays
Arrays can be sparse
var names = new Array();
A
()
names[0] = "Joe";
names[100000] = "Juan";

Arrays can be resized


Regardless of how arrays is created, you can do:
myArray.length = someNewLength;
myArray[anyNumber] = someNewValue;
myArray.push(someNewValue)
These are legal
g regardless
g
of which way
y myArray
y
y was made

Arrays have methods


push, pop, join, reverse, sort, concat, slice, splice, etc.
See API reference

Regular objects can be treated like arrays


29

You can use numbers (indexes) as object properties

Arrays Example
function arrayLoops() {
var names =
["Joe", "Jane", "John"];
printArray1(names);
printArray2(names);
names.length = 6;
printArra 1(names)
printArray1(names);
printArray2(names);
}
function printArray1(array) {
for(var i=0; i<array.length; i++) {
console.log("[printArray1] array[%o] is %o", i, array[i]);
}
}
console.log is a printf-like way to print output in Firebug

30

Console window. For testing/debugging only.


function printArray2(array) {
for(var i in array) {
console.log("[printArray2] array[%o] is %o", i, array[i]);
}
Direct call for interactive testing in Firebug console.
}
(Cut/paste all code into console command line.)
arrayLoops();

2010 Marty Hall

Strings and
Regular
g
Expressions
p
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.

String Basics
You can use double or single quotes
var names = [["Joe"
Joe , 'Jane'
Jane , "John"
John , 'Juan'];
Juan ];

You can access length property


E.g., "foobar".length returns 6

Numbers
N b
can be
b converted
t d to
t strings
ti
Automatic conversion during concatenations.
var val = 3 + "abc" + 5; // Result is "3abc5"

Conversion
C
i with
ith fi
fixedd precision
ii
var n = 123.4567;
var val = n.toFixed(2); // Result is 123.46 (not 123.45)

Strings can be compared with ==


"foo" == 'foo' returns true

Strings can be converted to numbers


var i = parseInt("37 blah"); // Result is 37 ignores blah
var d = parseFloat("6.02 blah"); // Ignores blah
32

Core String Methods


Simple methods similar to Java
charAt, indexOf, lastIndexOf, substring, toLowerCase,
toUpperCase

Methods that use regular expressions


match, replace, search, split

HTML methods
anchor, big, bold, fixed, fontcolor, fontsize, italics, link,
small, strike, sub, sup
"test".bold().italics().fontcolor("red") returns
'<font color="red"><i><b>test</b></i></font>'

These are technically


y nonstandard methods, but supported
pp
in all major browsers
But I prefer to construct HTML strings explicitly anyhow
33

Regular Expressions
You specify a regexp with /pattern/
Not
N with
i h a String
S i as in
i Java
J

Most special characters same as in Java/Unix/Perl

^,, $,, .
\
*, +, ?
{n} {n,}
{n},
{n }
[]
\s, \S
\w \W
\w,

beginning,
g
g, end of string,
g, anyy one char
escape what would otherwise be a special character
0 or more, 1 or more, 0 or 1 occurrences
exactly n,
n n or more occurrences
grouping
whitespace, non-whitespace
word char (letter or number),
number) non-word
non word char

Modifiers
/pattern/g do global matching (find all matches, not just first one)
/pattern/i do case-insensitive matching
/pattern/m do multiline matching
34

Regular Expression: Examples

35

More Information on Regular


Expressions
Online API references given earlier
(S RegExp
(See
R E class)
l
)
http://www.w3schools.com/jsref/jsref_obj_regexp.asp
http://www.devguru.com/technologies/ecmascript/
http://www devguru com/technologies/ecmascript/
QuickRef/regexp.html

JavaScript
p Regular
g
Expression
p
Tutorials
http://www.evolt.org/article/Regular_Expressions_in_
JavaScript/17/36435/
http://www.javascriptkit.com/javatutors/re.shtml
h //
j
i ki
/j
/ h l

36

2010 Marty Hall

Wrap-up
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.

Summary
Use Firebug for testing and debugging
Bookmark
B k
k references
f
http://www.w3schools.com/js/

Embedding in browser
<script src="blah.js" type="test/javascript"></script>
Use XHTML or pseudo-HTML 5 syntax

Basic
B i JavaScript
J
S i t syntax
t
Declare local variables with var. No type declarations.
Java
Loops and conditionals similar to Java.

JavaScript arrays

38

Arrays are very different than in Java. Can have extra


properties.
ti Can
C resize
i them.
th
Can
C be
b sparse.
But, you usually treat them like normal arrays, except that
pop and push are widely used.

2010 Marty Hall

Questions?
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.

You might also like