Javascript CPI 101: Meeting 8 Rick Chimera School of Computing and Informatics

advertisement
CPI 101: Meeting 8
Javascript
Rick Chimera
School of Computing and Informatics
Arizona State University
Tempe, Arizona USA
Why Learn Specifically about Javascript?
It is the most popular scripting language
Used for web pages and many other uses
Great way to make web pages dynamic
Example of computer programming language that is:

“interpreted”

Easy to code and powerful at the same time
Programming in Javascript
Use reserved words such as “var”, “function”, “if”, many more
Syntax is critical for the computer to read the code.

Weird characters like { } ( ) [ ] ! ; & and more
Extra space characters and line-feeds are not critical for the computer to read the code, but are
a good idea to help humans read the code.

Computer is never wrong, the program will do exactly what
you tell it to do. Be prepared for:

Humiliation

Frustration

Ultimately, great satisfaction
Interpreted versus Compiled Languages
Interpreted
Can be run immediately by
computer “environment”
(web browser or other
program that knows the
language)

Good: quick

Bad: hard to find silly errors like typos.
Compiled
Must be run through a
program called a “compiler” in
order to be run by computer

Good: compiler can help find errors

Bad: (next slide)
Interpreted versus Compiled Languages (cont.)
Interpreted
Rapid cycle of edit-run

Bad: promotes “trial and error” coding
Usually can run new code
in existing situation
Compiled
Slower cycle of edit-compilerun

Punch cards: hours/days

1980 computers: tens of minutes

2007 computers: tens of seconds
Usually have to restart entire
program which resets
variables.
Modern Stored Programs (from previous class)
Today’s computer programs incorporate a variety of features:
Sequences of steps that should be executed
Variables that store changing values
Hierarchical calls to many levels of subroutines
Tests that place conditions on some activities
Iteration or recursion to handle repetitive activities
These are written in many different programming languages and
range from a few lines of code to millions.
What they hold in common is the idea that one can store programs
as data and interpret them to produce behavior.
Using Variables in Javascript
A stored program may need to keep track of things that change during its operation using one or
more variables, which:
Are place holders that store some form of information.
Take some initial value at the program’s outset.
Can change repeatedly during the program’s execution.
In Javascript it is a good idea to declare variables, but you are not
forced to do so.
var x;
var y = 4;
var temperature, greeting = “hello”;
temperature = 98.6;
x = greeting;
brand_new_undeclard_variable = 1;
tempreature = 101;
Assignment Statements are NOT Algebra
var x, y = 4;
x = y + 1;
What is value of x right now?
If we think about this like algebra, solve for y:
x–1=y+1–1
x – 1 = y (this does make sense algebraically)
Now consider the following assignment statement:
y = y + 1;
If try to make this algebra, solve for y:
y – y = y – y + 1;
0 = 1;
See!? Not algebra! It is simply an assignment statement.
Hierarchical Nature of Activities in Javascript
Many everyday activities have an obvious hierarchical structure:
Clean teeth: floss teeth, brush teeth, use mouth wash
Brush teeth: put paste on brush, clean inner, clean outer, rinse
In Javascript, we use functions to do this:
function clean_teeth() {
floss_teeth();
brush_teeth();
use_mouthwash();
}
function brush_teeth() { put_paste_on_brush(); clean_inner(); clean_outer(); rinse(); }
...and so on...
Subroutines in Stored Programs
We can produce hierarchical behavior in stored programs by:
Passing variables as arguments to subroutines when called
Returning results from subroutines when they are complete
In Javascript, subroutines are functions:
function brush_teeth( flavor ) {
put_paste_on_brush(flavor); clean_inner(); clean_outer(); rinse();
return “My mouth now tastes like ” + flavor;
}
This simplifies greatly construction and debugging of computer
programs because it makes them more modular and reusable.
Nearly all nontrivial programs have this hierarchical character.
Conditionals in Stored Programs (from previous
class)
We can produce conditional behavior in stored programs by:
Stating that an activity should continue until a test is met.
Stating that an activity should continue while a test is met.
Indicating that a step should happen only if a condition is met.
Such constructs simplify the construction of computer programs
because it makes them more flexible and adaptive.
Nearly all nontrivial stored programs have this conditional flavor.
Conditional Statements in Javascript
Several choices:
“if ... else”
“switch”
“while”
“do ... while”
As part of a “for” loop
Even more, too confusing for our purposes
Syntax of IF ... ELSE Statement in Javascript
if ( some condition is true )
execute this statement;
else
execute this other statement;
Parentheses, reserved words, and semi-colons are critical!
Starting with this slide, I use the color yellow to signify which
parts of these slides are the Javascript code rather than just talking
about Javascript code.
if ( x < 4 )
alert( “x is less than 4” );
else
alert( “x is not less than 4” );
IF ... ELSE Statement in Javascript (cont.)

else clause is optional:
if ( x < 4 )
alert (“x is less than 4”);
We can nest if ... else statements
if ( x < 4 )
{
if ( x < 0 )
alert( “oh no! x is less than zero!” );
else
alert( “x is less than 4” );
}
else
alert (“x is greater than 4”);

Iteration in Stored Programs (from previous class)
Conditionals often occur within iterative/looping constructs that:
Initialize the values of variables, including counters.
State one or more steps that should occur on each loop
Including incrementing/decrementing of any counters
Indicate the conditions for halting the iteration.
Iterative statements simplify the specification of stored programs
because it handles repetitive behavior.
Nearly all nontrivial computer programs incorporate either
iteration or recursion.
Iteration using the WHILE statement in Javascript
while ( condition )
execute this statement;
var x = 0;
while ( x < 10 )
{
print( x );
x = x + 1;
}
Will the above code print the number 0? The number 10?
Boundary cases can be the cause of subtle errors in programs.
Iteration using the FOR statement in Javascript
for ( initialize variables ; condition ; modify variables after loop )
execute this statement;
for ( x = 0 ; x < 10 ; x = x + 1 )
print( x );
Exact same behavior as the WHILE loop on the previous slide.
for ( x = 10 ; x < 10 ; x = x + 1 )
print( x );
Will this print out the number 10?
Object Notation
An object is a great way to store together things that should always
be kept together.
Javascript let's you build an object easily using the “dot notation”:
var car = new Object();
car.engine = “off”;
car.cost = 40000;
car.expensive = true;
The variables within an object are called its “properties”.
A variable within an object can be a function, in which case it is
called a “method”.

Object Notation (cont.)
You can add properties to an object at any time, but it is a good idea
to use a function to create an object:
function Car( cost ) {
this = new Object();
this.engine = “off”;
this.cost = cost;
if ( this.cost < 30000)
this.expensive = false;
else
this.expensive = true;
}
var mycar = Car( 40000 );
Notice the variable named “this”. It is special. It means “the
particular instance of the object created, which will be returned by
the function automatically without the need for a return statement.”
Object Instances
var bmw = Car( 40000 );
var kia = Car( 10000 );
bmw and kia are two different instances of the Car object.
Programmers do this all the time to create tens, hundreds, even
thousands of different instances of the same object.
Objects within objects
Objects can contain other objects:
var person = new Object();
person.name = “Joe”;
person.car = Car( 40000 );
if ( person.car.expensive == true )
alert( person.name + “ owns an expensive car.”);
Static Web Pages
Web pages use HTML to display content.
HTML stands for HyperText Markup Language.
HTML uses angle brackets to denote entities.
Most entities must have a beginning statement and an ending
statement that prepends the entity name with a slash (/)
<html>
<head></head>
<body>
Hello world
</body>
</html>
Javascript in Web Pages
Usually within the <head> entity, we define our javascript
There are two ways to do it, in-line or by loading a file.
<head>
<script type = “text/javascript”>
var x = “hello world”;
document.write ( x );
</script>
<script type = “text/javascript” src=”myfile.js”></script>
</head>
Javascript in Web Pages
Sometimes a web site will “obfuscate” their javascript code so
that others cannot easily copy it and use it.
Typical obfuscation approaches are:
Really short variable/function names such that it is hard to determine the purpose of the
variable/function.


Remove whitespace so it all runs together and his quite difficult for humans to read.
Javascript helps make web pages dynamic
 Validation of input fields
 Changing an image when mouse enters or leaves an image
(“rollover”)
 Setting internal variables to keep track of things
 Reading or setting “cookies” on the local computer
 Dynamic menus
 ...and more...
Further Learning Resources
 I strongly suggest the W3Schools web site. This is run by the
W3C organization which stands for World Wide Web
Consortium, a non-profit group that promotes web standards
and advances.
For html, go to http://www.w3schools.com/html
For javascript, go to http://www.w3schools.com/js
Or, google “javascript tutorial” and find one you like.
Summary
 Javascript is easy, fun, frustrating, mind-boggling
 Javascript impacts your life every time you view a dynamic
web page.
 With perseverance you can read and understand web pages
and the javascript that makes them have a better “user
experience”.
 Now, let's look at some real web site code and see what it
does!
Download