08 Javascript 2
08 Javascript 2
Taif University
College of Computers and Information Technology
About JavaScript
● JavaScript is not Java, or even related to Java
● The original name for JavaScript was “LiveScript”
● The name was changed when Java became popular
● Now that Microsoft no longer likes Java, its name for their
JavaScript dialect is “Active Script”
● Statements in JavaScript resemble statements in Java,
because both languages borrowed heavily from the C
language
● JavaScript should be fairly easy for Java programmers to learn
● However, JavaScript is a complete, full-featured, complex language
● JavaScript is seldom used to write complete “programs”
● Instead, small bits of JavaScript are used to add functionality to
HTML pages
● JavaScript is often used in conjunction with HTML “forms”
● JavaScript is reasonably platform-independent
0
Using JavaScript in a browser
● JavaScript code is included within <script> tags:
● <script type="text/javascript">
document.write("<h1>Hello World!</h1>") ;
</script>
● Notes:
● The type attribute is to allow you to use other scripting languages
(but JavaScript is the default)
● This simple code does the same thing as just putting <h1>Hello
World!</h1> in the same place in the HTML document
● The semicolon at the end of the JavaScript statement is optional
but preferred
0
JavaScript isn’t always available
● Some old browsers do not recognize script tags
● These browsers will ignore the script tags but will display the included
JavaScript
● To get old browsers to ignore the whole thing, use:
<script type="text/javascript">
<!--
document.write("Hello World!")
//-->
</script>
● The <!-- introduces an HTML comment
● To get JavaScript to ignore the HTML close comment, -->, the // starts a
JavaScript comment, which extends to the end of the line
● Some users turn off JavaScript
● Use the <noscript>message</noscript> to display a message in place of
whatever the JavaScript would put there
0
HTML names in JavaScript
● In HTML the window is the global object
● It is assumed that all variables are properties of this
object, or of some object descended from this object
● The most important window property is document
● HTML form elements can be referred to by
document.forms[formNumber].elements[elementNumber]
● Every HTML form element has a name attribute
● The name can be used in place of the array reference
● Hence, if
● <form name="myForm">
<input type="button" name="myButton" ...>
● Then instead of document.forms[0].elements[0]
● you can say document.myForm.myButton
0
Example
● John Smith's email:
x
<script language=javascript>
<!--
var name = "smithj"
var host1 = "seas.up"
var host2 = "enn.edu"
var addr =
document.write("<a href=mai" + "lto:" +
name + "@" + host1 + host2 +
"?subject=CIT597:" +
">" + "John Smith" + "</a>")
//-->
</script>
<noscript>
smithj at seas
</noscript>
0
Where to put JavaScript
● JavaScript can be put in the <head> or in the <body> of an
HTML document
● JavaScript functions should be defined in the <head>
● This ensures that the function is loaded before it is needed
● JavaScript in the <body> will be executed as the page loads
● JavaScript functions can be put in a separate .js file
● <script src="myJavaScriptFile.js"></script>
● Put this in the <head>
● An external .js file lets you use the same JavaScript on multiple HTML
pages
● The external .js file cannot itself contain a <script> tag
● JavaScript can be put in an HTML form object, such as a button
● This JavaScript will be executed when the form object is used
0
Primitive data types
● JavaScript has three “primitive” types: number, string, and
boolean, and two special values, null and undefined
● Everything else is an object
● Numbers are always stored as floating-point values
● Strings may be enclosed in single quotes or double quotes
● Strings can contains \n (newline), \" (double quote), etc.
● Booleans are either true or false
● false value: 0, "0", empty strings, undefined, null, and NaN,
● other values are true
0
undefined and null
● There are special values undefined and null
● undefined is the only value of its “type”
● This is the value of a variable that has been declared but not
defined, or an object property that does not exist
● void is an operator that, applied to any value, returns the
value undefined
● null is an “object” with no properties
● null and undefined are == but not ===
0
Numbers
● In JavaScript, all numbers are floating point
● Special predefined numbers:
● Infinity, Number.POSITIVE_INFINITY -- the result of dividing a positive
number by zero
● Number.NEGATIVE_INFINITY -- the result of dividing a negative number
by zero
● NaN, Number.NaN (Not a Number) -- the result of dividing 0/0
● NaN is unequal to everything, even itself
● There is a global isNaN() function
● Number.MAX_VALUE -- the largest representable number
● Number.MIN_VALUE -- the smallest (closest to zero) representable
number
0
Variables
● Variables can be declared with a var statement:
● var pi = 3.1416, x, y, name = "Dr. Dave" ;
● Variables names must begin with a letter or underscore
● Variable names are case-sensitive
● Variables are untyped (they can hold values of any type)
● There are only two scopes: local and global
● Variables declared within a function are local to that function
(accessible only within that function)
● Variables declared outside a function are global (accessible from
anywhere on the page)
● Variables can also be declared implicitly, simply by
assigning a value to them
● Implicitly declared variables are always global
0
Operators, I
● Because most JavaScript syntax is borrowed from C (and is
therefore just like Java), we’ll go through it quickly
0
Operators, II
● String operator:
+
● The conditional operator:
condition ? value_if_true : value_if_false
● Special equality tests:
● == and != try to convert their operands to the same type before performing
the test
● The rules for how this occurs are complex and intransitive; you should avoid
using these operators
● === and !== consider their operands unequal if they are of different types
● These operators work like == and != in C or Java
● Additional operators (to be discussed):
new typeof void delete
0
Comments
● Comments are as in C or Java:
● Between // and the end of the line
● Between /* and */
● Java’s javadoc comments, /** ... */, are treated just the
same as /* ... */ comments; they have no special
meaning in JavaScript
0
Statements, I
0
Statements, II
● The switch statement:
switch (expression) {
case label :
statement;
break;
case label :
statement;
break;
...
default : statement;
}
● Other familiar statements:
● break;
● continue;
● The empty statement, as in ;; or { }
0
JavaScript is not Java
● By now you should have realized that you already know a
great deal of JavaScript
● So far we have talked about things that are the same as in Java
● JavaScript has some features that resemble features in Java:
● JavaScript has Objects and primitive data types
● JavaScript has qualified names; for example,
document.write("Hello World");
● JavaScript has Events and event handlers
● Exception handling in JavaScript is almost the same as in Java
● JavaScript has some features unlike anything in Java:
● Variable names are untyped: the type of a variable depends on the
value it is currently holding
● Objects and arrays are defined in quite a different way
● JavaScript has with statements and a new kind of for statement
0
Array literals
● JavaScript has array literals, written with brackets and
commas
● Example: color = ["red", "yellow", "green", "blue"];
● Arrays are zero-based: color[0] is "red"
● If you put two commas in a row, the array has an
“empty” element in that location
● Example: color = ["red", , , "green", "blue"];
● color has 5 elements
● However, a single comma at the end is ignored
● Example: color = ["red", , , "green", "blue”,]; still has 5 elements
0
Four ways to create an array
● You can use an array literal:
var colors = ["red", "green", "blue"];
● You can use new Array() to create an empty array:
● var colors = new Array();
● You can add elements to the array later:
colors[0] = "red"; colors[2] = "blue"; colors[1]="green";
● You can use new Array(n) with a single numeric
argument to create an array of that size
● var colors = new Array(3);
● You can use new Array(…) with two or more arguments
to create an array containing those values:
● var colors = new Array("red","green", "blue");
0
The length of an array
0
Arrays and objects
● Arrays are objects
● car = { myCar: "Saturn", 7: "Mazda" }
● car[7] is the same as car.7
● car.myCar is the same as car["myCar"]
● If you know the name of a property, you can use dot
notation: car.myCar
● If you don’t know the name of a property, but you have
it in a variable (or can compute it), you must use array
notation: car["my" + "Car"]
0
Array functions
● If myArray is an array,
● myArray.sort() sorts the array alphabetically
● myArray.sort(function(a, b) { return a - b; }) sorts
numerically
● myArray.reverse() reverses the array elements
● myArray.push(…) adds any number of new elements to the
end of the array, and increases the array’s length
● myArray.pop() removes and returns the last element of the
array, and decrements the array’s length
● myArray.toString() returns a string containing the values of
the array elements, separated by commas (but not enclosed in
brackets)
0
Some string methods
● charAt(n)
● Returns the nth character of a string
● concat(string1, ..., stringN)
● Concatenates the string arguments to the recipient string
● indexOf(substring)
● Returns the position of the first character of substring in the recipient
string, or -1 if not found
● indexOf(substring, start)
● Returns the position of the first character of substring in the given string
that begins at or after position start, or -1 if not found
● lastIndexOf(substring), lastIndexOf(substring, start)
● Like indexOf, but searching starts from the end of the recipient string
0
Functions I
● Functions should be defined in the <head> of an
HTML page, to ensure that they are loaded first
● One syntax for defining a function is:
function name(arg1, …, argN) { statements }
● The function may contain return value; statements
● Any variables declared within the function are local to it
● The syntax for calling a function is just
name(arg1, …, argN)
● Simple parameters are passed by value, objects are
passed by reference
0
Functions II
● In JavaScript, functions are values, and can be assigned, passed
as parameters, etc., just like other values
● Within a program, you can use
var foo = function foo() {...}
instead of
function foo() {...}
● The first form should be preferred for a couple of reasons:
● The first form makes it clear that foo is a value
● The second form will cause the function to be hoisted: moved to the top of
the scope in which it is defined
● The second form cannot be the first thing in a statement
● The second form is illegal inside an if statement, but most browsers allow
it anyway (and do different things with it)
0
Regular expressions
● A regular expression can be written in either of two ways:
● Within slashes, such as re = /ab+c/
● With a constructor, such as re = new RegExp("ab+c")
● Regular expressions are almost the same as in Perl or Java (only
a few unusual features are missing)
● string.match(regexp) searches string for an occurrence of
regexp
● It returns null if nothing is found
● If regexp has the g (global search) flag set, match returns an array of
matched substrings
● If g is not set, match returns an array whose 0th element is the matched
text, extra elements are the parenthesized subexpressions, and the index
property is the start position of the matched substring
0
More string methods
● match(regexp)
● Returns an array containing the results, or null if no match is found
● On a successful match:
● If g (global) is set, the array contains the matched substrings
● If g is not set:
● Array location 0 contains the matched text
● Locations 1... contain text matched by parenthesized groups
● The array index property gives the first matched position
● replace(regexp, replacement)
● Returns a new string that has the matched substring replaced with the
replacement
● search(regexp)
● Returns the position of the first matched substring in the given string,
or -1 if not found.