Lecture 4
The Basics of JavaScript
Web Programming
Overview
Overview of JavaScript
Syntactic Characteristics
Primitives, Operations and
Expressions
Math, Number, String and Date
objects
Screen Output
Control Statements
Objects, Arrays and Functions
Origins of JavaScript
Originally developed by Netscape, as
LiveScript
Became a joint venture of Netscape and
Sun in 1995, renamed JavaScript
Now standardized by the European
Computer Manufacturers Association as
ECMA-262
An XHTML-embedded scripting language
We will call collections of JavaScript code
scripts, not programs
JavaScript and Java
JavaScript and Java are only related
through syntax
JavaScript is dynamically typed
JavaScript’s support for objects is
very different
JavaScript is interpreted
– Source code is embedded inside XHTML
doc, there is no compilation
Uses of JavaScript
Transfer of some load from server to
client
User interactions through forms
– Events easily detected with JavaScript
– E.g. validate user input
TheDocument Object Model makes it
possible to create dynamic HTML
documents with JavaScript
JavaScript Execution
JavaScript scripts are executed
entirely by the browser
Once downloaded there is no
exchange of information with the
server
– JavaScript programs can issue HTTP
requests and load other pages
JavaScript scripts do not require the
Java VM to be loaded
Thus JavaScript scripts tend to be fast
Embedding in XHTML docs
Either directly, as in
<script type = “text/javascript”>
-- JavaScript script –
</script>
Orindirectly, as a file specified in the
src attribute of <script>, as in
<script type = “text/javascript”
src = “myScript.js”>
</script>
Syntactic Characteristics
Identifier form: begin with a letter or
underscore, followed by any number of letters,
underscores, and digits
– Case sensitive
Around 25 reserved words, plus future reserved
words
Comments: both // and /* … */
Scripts are usually hidden from browsers that
do not include JavaScript interpreters by putting
them in special comments
<!--
-- JavaScript script –
//-->
Primitives
All primitive values have one of the five
types: Number, String, Boolean, Undefined,
or Null
All numeric values are stored in double-
precision floating point
String literals are delimited by either ' or "
Boolean values are true and false
The only Null value is null
The only Undefined value is undefined
Number, String, and Boolean have wrapper
objects (Number, String, and Boolean)
Declaring Variables
JavaScript is dynamically typed – any
variable can be used for anything
The interpreter determines the type of a
particular occurrence of a variable
Variables can be explicitly declared
using either var or let
var sum = 0,
today = "Monday",
flag = false;
Variables declared with let can have Block
Scope but those declared with var cannot.
Numeric Operators
Math and Number Objects
The Math Object provides floor,
round, max, min, trig functions, etc.
– e.g., Math.cos(x)
The Number Object has some useful
properties
Number Object
Anarithmetic operation that creates
overflow returns NaN
NaNis not == to any number, not
even itself
Test for it with isNaN(x)
String Object
The number of characters in a string
is stored in the length property
var str = “George”;
var len = str.length;
Common methods:
String Object
Stringcatenation operator +
Coercions
– Catenation coerces numbers to strings
– Numeric operators (other than +) coerce
strings to numbers (if either operand of + is a
string, it is assumed to be catenation)
Example:
“August” + 1977 “August1977”
7 * ”3” 21 (if the string operand couldn’t be
converted to a number the conversion would produce
NaN )
Date Object
Create one with the Date constructor (no
params)
var today = new Date();
Local time methods of Date:
– toLocaleString – returns a string of the date
– getDate – returns the day of the month
– getMonth – returns the month of the year (0 – 11)
– getDay – returns the day of the week (0 – 6)
– getFullYear – returns the year
– getTime – returns the number of milliseconds since
January 1, 1970
– getHours – returns the hour (0 – 23)
– getMinutes – returns the minutes (0 – 59)
– getMilliseconds – returns the millisecond (0 – 999)
Screen Output
JavaScript models the XHTML document with the
Document object
The model for the browser display window is the
Window object
– The Window object has two properties, document and window,
which refer to the Document and Window objects, respectively
The Document object has a method, write, which
dynamically creates content
– The parameter is a string, often concatenated from parts,
some of which are variables
document.write(“Answer:” + result + “<br />”);
– The parameter is sent to the browser, so it can be anything
that can appear in an XHTML document (any XHTML tags)
Screen Output
The Window object has three methods for
creating dialog boxes
1. Alert
alert(“The sum is:” + sum + ”\n");
– Parameter is plain text, not XHTML
– Opens a dialog box which displays the
parameter string and an OK button
It waits for the user to press the OK button
Screen Output
2. Confirm
var question = confirm("Do you want
to continue this download?");
– Opens a dialog box and displays the
parameter and two buttons, OK and Cancel
– Returns a Boolean value, depending on which
button was pressed (it waits for one)
Screen Output
3. Prompt
var x= prompt("What is your name?", “ ");
– Opens a dialog box and displays its string parameter,
along with a text box and two buttons, OK and
Cancel
– The second parameter is for a default response if the
user presses OK without typing a response in the text
box
roots.htm
Control Statements
Control expressions – three kinds
1. Primitive values :
- If it is a string, it is true unless it is empty or "0“
- If it is a number, it is true unless it is zero
2. Relational Expressions
- The usual six: ==, !=, <, >, <=, >=
- Operands are coerced if necessary
- If one is a string and one is a number, it attempts to convert the string
to a number
- If one is Boolean and the other is not, the Boolean operand is
coerced to a number (1 or 0)
- The unusual two: === and !==
Same as == and !=, except that no coercions are done (operands must be identical)
3. Compound Expressions
-The usual operators: &&, ||, and !
Conditionals
Selection statements – “if” and “if…
else“
if (a > b)
document.write(“a is greater than b <br
/>”);
else {
a = b;
document.write(“a was not greater than
b, now they are equal <br />”);
}
The switch statement
borders.htm
Loops
while (control_expression) statement or
compound stmt
for (init; control; increment)
statement or compound stmt
– init can have declarations, but the scope of
such variables is the whole script
date.htm
do statement or compound
while(control_expression)
Objects
Object Creation and Modification
– Objects can be created with new
– The most basic object is one that uses the
Object constructor, as in
var myObject = new Object();
– The new object has no properties - a
blank object
– Properties can be added to an object, any
time
Objects (cont.)
Objects properties
var myAirplane = new Object();
myAirplane.make = "Cessna";
myAirplane.model = "Centurian";
–Objects can be nested, so a property could
be itself another object, created with new
–Properties can be accessed by dot
notation or in array notation, as in
var property1 = myAirplane["model"];
–A property can be deleted with delete
delete myAirplane.model;
Objects (cont.)
Another Loop Statement (an iterator)
for (identifier in object) statement or
compound
Example
for (var prop in myAirplane)
document.write(myAirplane[prop] + "<br />");
Arrays
Array elements can be primitive values or
references to other objects
Array objects can be created in two ways, with new,
or by assigning an array literal
var myList = new Array(24, "bread",true);
var myList1 = [24, "bread", true];
Length is dynamic - the length property stores the
length
– length property is writeable
myList.length = 150;
insert_names.htm
Array (cont.)
join – e.g., var listStr = list.join(",");
sort – e.g., names.sort();
– Coerces elements to strings and puts them in alphabetical order
concat – e.g., newList = list.concat(47, 26);
slice – e.g., listPart = list.slice(2, 4);
listPart2 = list.slice(2);
toString Coerces elements to strings, if necessary, and catenates
them together, separated by commas (exactly like join(", "))
reverse – e.g., newlist = list.reverse()
push, pop, unshift, and shift
2D Arrays (nested arrays)
nested_arrays.htm
Functions
function function_name([formal_parameters]) {
-- body –
return value
}
Return value is the parameter of return
– If there is no return or if return has no parameter,
undefined is returned
Variables explicitly declared in a function are local
Functions – parameters
Parameters are passed by value, but when
a reference variable is passed, the
semantics are pass-by-reference
There is no type checking of parameters,
nor is the number of parameters checked
– excess actual parameters are ignored, excess
formal parameters are set to undefined
All parameters are sent through a property
array, arguments, which has the length
property
parameters.htm