Web Development Technology
Introduction to JavaScript
Language timeline
category 1960s 1970s 1980s 1990s 2000s
scientific Fortran Matlab
business Cobol DBMSes SQL VB
functional Lisp ML, Scheme Erlang Haskell F#
imperative/ Algol Pascal, C, Ada, C++ Java C#
procedural Smalltalk
scripting BASIC Perl Python,
Ruby, PHP,
JavaScript
logical Prolog CLP(R)
2
History of JavaScript?
• created in 1995 by Brandon Eich of Netscape/Mozilla
"JS had to "look like Java" only less so, be Java’s dumb kid brother or
boy-hostage sidekick. Plus, It had to be done in ten days or something
worse than JS would have happened.” - Brandon Eich
Originally called “LiveScript” to match Netscape branding
Renamed to JavaScript to capitalize on the popularity of
Java
submitted as a standard to ECMA in 1997 as "ECMAScript"
• not directly related to Java
Eich claims he was most influenced by Self and Scheme
some JS syntax, libraries, etc. are ripped off by C++, Java, C
D. Crockford: "JavaScript is Lisp in C's clothing."
3
JavaScript today
• Possibly the most used programming language today (!!)
mostly used for client-side web page scripting, but
increasingly used to build server apps, other programs
current standardized version: ECMAScript 5 (2009)
• Is JavaScript a bad programming language??
had bad browser behavior, slow, poor web coders, etc.
recent implementations are faster, better, more stable
JS in browser works with "DOM" (Document Object Model)
related JS+web technologies: Ajax, JSON, jQuery, etc.
spin-off languages: JScript (MS), ActionScript (Adobe), etc.
4
JavaScript vs. C++ or Java
• interpreted, not compiled
dynamic typing
first-class functions; nested functions; closures
a structured, imperative object-oriented, scripting lang.
prototype-based object and inheritance system
sophisticated first-class resizable array type
first-class regular expression support
• more relaxed syntax and rules
fewer and "looser" data types
variables don't always need to be declared
key construct is first-class function rather than the class
5
Primitive data types
• JavaScript has three “primitive” types: number, string, and
boolean
Everything else is an object
• Numbers are always stored as floating-point values
Hexadecimal numbers begin with 0x
Some platforms treat 0123 as octal, others treat it as decimal
• Strings may be enclosed in single quotes or double quotes
Strings can contains \n (newline), \" (double quote), etc.
• Booleans are either true or false
– 0, "0", empty strings, undefined, null, and NaN are false ,
other values are true
6
JavaScript Data Types
• JavaScript variables can hold numbers like 253, 3.142
and text values like “IT Group".
• In programming, text values are called text strings.
• JavaScript can handle many types of data, but for now,
just think of numbers and strings.
Strings are written inside double or single quotes.
Numbers are written without quotes.
If you put a number in quotes, it will be treated as a text
string.
7
Operators
• Arithmetic
• Relational
• Logical
• Bitwise
• Assignment
• Miscellaneous
8
JavaScript Datatypes
• Object
• String An object
• Number An array
• Bigint A date
• Boolean
• Undefined
• Null
• Symbol
9
Variables
• Variables are declared with a let or var statement:
– let pi = 3.1416, x, y, name = “Dr. Chris
Quist" ;
Variables names must begin with a letter or underscore
Variable names are case-sensitive
Variables are untyped (they can hold values of any type)
The word let or var is optional (but it’s good style to
use it)
• 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)
10
Arithmetic Operators
• Binary Operators
Operator Meaning Example
+ Addition A+B
- Subtraction A–B
* Multiplication A*B
/ Division A/B
% Modulus A%B
** Exponentiation A**B
• Unary Operators
Operator Meaning Example
++ Increment A++
-- Decrement A--
11
Relational Operators
Operator Meaning Example
== equal to A==B
=== equal value and equal type A === B
!= not equal A != B
!== not equal value or not equal type A !== B
> greater than A>B
< less than A<B
>= greater than or equal to A >= B
<= less than or equal to A <= B
? ternary operator
12
Using JavaScript in a browser
• JavaScript code is included within <script> tags:
– <script type="text/javascript">
[Link]("<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
– You need semicolons if you put two or more statements on the same
line
– It’s probably a good idea to keep using semicolons
13
Dealing with old browsers
• 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">
<!--
[Link](“Testing Data Output….!")
//-->
</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
14
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 can be put in a separate .js file
– <script src="[Link]"></script>
Put this HTML wherever you would put the actual JavaScript code
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 HTML form object, such as a button
This JavaScript will be executed when the form object is used
15
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
16
Statements
• Most JavaScript statements are also borrowed from C
Assignment: greeting = "Hello, " + name;
Compound statement:
{ statement; ...; statement }
If statements:
if (condition) statement;
if (condition) statement; else statement;
Familiar loop statements:
while (condition) statement;
do statement while (condition);
for (initialization; condition; increment) statement;
17
Statements
• 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 { }
18
JavaScript is not Java
• By now you should have realized that you already know a
great deal about 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,
[Link]("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
19
Exception handling
• Exception handling in JavaScript is almost the same as in
Java
• throw expression creates and throws an exception
The expression is the value of the exception, and can be of any
type (often, it's a literal String)
• try {
statements to try
} catch (e) { // Notice: no type
declaration for e
exception-handling statements
} finally { // optional, as usual
code that is always executed
}
With this form, there is only one catch clause
20
Exception handling
• try {
statements to try
} catch (e if test1) {
exception-handling for the case that test1 is true
} catch (e if test2) {
exception-handling for when test1 is false and test2 is true
} catch (e) {
exception-handling for when both test1and test2 are false
} finally { // optional, as usual
code that is always executed
}
• Typically, the test would be something like
e == "InvalidNameException"
21
Running JS code in a browser
<html>
<head>
<script src="[Link]"
type="text/javascript"></script>
</head>
<body>
<p>My web page</p> ...
</body>
</html>
22
JavaScript syntax
Variables
{var|let|const} name [= expression];
• Examples:
var age = 32;
let weight = 127.4;
const clientName = "Connie Client";
• Variables declared are case sensitive
• Types not specified, but JS does have types
Number, Boolean, String, Array, Object,
Function, Null, Undefined
can find out a variable's type by calling typeof
25
Numbers
var enrollment = 99;
var medianGrade = 2.8;
var credits = 5 + 4 + (2 * 3);
• integers and real numbers are the same type
(no int vs. double)
• same operators: + - * / % ++ -- = += -= *= /= %=
similar precedence to C++ or Java
many operators auto-convert types: "2" * 3 is 6
26
Number properties/methods
Number object "static" properties
Number.MAX_VALUE largest possible number, roughly 10308
Number.MIN_VALUE smallest positive number, roughly 10-324
[Link] Not-a-Number; result of invalid computations
Number.POSITIVE_INFINIT infinity; result of 1/0
Y
Numbernegative
Number.NEGATIVE_INFINIT instanceinfinity;
methods result of -1/0
Y
.toString([base]) convert a number to a string with optional base
.toFixed(digits) fixed-point real with given # digits past decimal
.toExponential(digits) convert a number to scientific notation
.toPrecision(digits) floating-point real, given # digits past decimal
global methods related to numbers
isNaN(expr) true if the expression evaluates to NaN
isFinite(expr) true if expr is neither NaN nor an infinity
27
The Math object
var rand1to10 = [Link]([Link]() * 10 +
1);
var three = [Link]([Link]);
• Math methods: abs, ceil, cos, floor, log, max,
min, pow, random, round, sin, sqrt, tan
• properties: E, PI
28
Math properties/methods
Math.E e, base of natural logarithms: 2.718...
Math.LN10, Math.LN2, natural logarithm of 10 and 2;
Math.LOG2E, Math.LOG10E logarithm of e in base 2 and base 10
[Link] , circle's circumference/diameter: 3.14159...
Math.SQRT1_2, Math.SQRT2 square roots of 1/2 and 2
[Link](n) absolute value
[Link]/asin/atan(n) arc-sin/cosine/tangent of angle in radians
[Link](n) ceiling (rounds a real number up)
[Link]/sin/tan(n) sin/cosine/tangent of angle in radians
[Link](n) en, e raised to the nth power
[Link](n) floor (rounds a real number down)
[Link](n) natural logarithm (base e)
[Link]/min(a, b...) largest/smallest of 2 or more numbers
[Link](x, y) xy, x raised to the yth power
[Link]() random real number k in range 0 ≤ k < 1
[Link](n) round number to nearest whole number
[Link](n) square root 29
Comments (same as C++)
// single-line comment
/*
multi-line comment
multi-line comment
*/
• (identical to Java's comment syntax)
30
Strings
var s = "Connie Client";
var firstName = [Link](0, [Link](" "));
var len = [Link]; // 13
var s2 = 'Melvin Merchant'; // can use "" or
''
• String methods: charAt, charCodeAt,
fromCharCode, indexOf, lastIndexOf, replace,
split, substring, toLowerCase, toUpperCase
charAt returns a one-letter string (there is no char type)
length is a property (not a method as in Java)
• concatenation with + : 1 + 1 is 2, but "1" + 1 is "11"
• strings can be compared with <, <=, ==, !=, >, >=
31
String methods
[Link](exp converts ASCII integer → String
r)
.charAt(index) returns character at index, as a String
.charCodeAt(index) returns ASCII value at a given index
.concat(str...) returns concatenation of string(s) to this one
.indexOf(str[,start]) first/last index at which given string begins in
.lastIndexOf(str[,start this string, optionally starting from given index
])
.match(regexp) returns any matches for this string against the
given string or regular expression ("regex")
.replace(old, new) replaces first occurrence of old string or regular
expr. with new string (use regex to replace all)
.search(regexp) first index where given regex occurs
.slice(start, end) substr. from start (inclusive) to end (exclusive)
.substring(start, end)
.split(delimiter[,limit break apart a string into an array of strings
]) 32
More about Strings and numbers
• escape sequences behave as in C++: \' \" \& \n \t \\
• convert string to number with parseInt, parseFloat:
var count = 10;
var s1 = "" + count; // "10"
var s2 = count + " bananas, ah ah ah!";
var n1 = parseInt("42 is the answer"); // 42
var n2 = parseInt("0x2A", 16); // 42
var n3 = parseFloat("3.1415"); // 3.1415
var bad = parseInt("booyah"); // NaN
• access the letters of a String with [] or charAt:
var firstLetter = s[0];
var firstLetter = [Link](0);
var lastLetter = [Link]([Link] - 1);
33
Array literals
• You don’t declare the types of variables in JavaScript
• 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
34
Four ways to create an array
• You can use an array literal:
let colors = ["red", "green", "blue"];
• You can use new Array() to create an empty array:
– let 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
– let colors = new Array(3);
• You can use new Array(…) with two or more
arguments to create an array containing those values:
– let colors = new Array("red","green", "blue");
35
The length of an array
• If myArray is an array, its length is given by
[Link]
• Array length can be changed by assignment beyond the
current length
Example: var myArray = new Array(5);
myArray[10] = 3;
• Arrays are sparse, that is, space is only allocated for
elements that have been assigned a value
Example: myArray[50000] = 3; is perfectly OK
But indices must be between 0 and 232-1
• As in C and Java, there are no two-dimensional arrays; but
you can have an array of arrays: myArray[5][3]
36
Arrays and objects
• Arrays are objects
• car = { myCar: "Saturn", 7:
"Mazda" }
– car[7] is the same as car.7
– [Link] is the same as car["myCar"]
• If you know the name of a property, you can use
dot notation: [Link]
• 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"]
37
Array functions
• If myArray is an array,
– [Link]() sorts the array alphabetically
– [Link](function(a, b) { return a -
b; }) sorts numerically
– [Link]() reverses the array elements
– [Link](…) adds any number of new elements
to the end of the array, and increases the array’s length
– [Link]() removes and returns the last element of
the array, and decrements the array’s length
– [Link]() returns a string containing the
values of the array elements, separated by commas
38
The for…in statement
• You can loop through all the properties of an object with
for (variable in object) statement;
Example: for (var prop in course) {
[Link](prop + ": " +
course[prop]);
}
Possible output: teacher: Dr. Dickson
number: BITM203
The properties are accessed in an undefined order
If you add or delete properties of the object within the loop, it is
undefined whether the loop will visit those properties
Arrays are objects; applied to an array, for…in will visit the
“properties” 0, 1, 2, …
Notice that course["teacher"] is equivalent to
[Link]
– You must use brackets if the property name is in a
39
The with statement
with (object) statement ;
•Uses the object as the default prefix for variables
in the statement
•For example, the following are equivalent:
– with ([Link]) {
[Link] = compute([Link]) ;
}
– [Link] =
compute([Link]);
•One of my books hints at mysterious problems
resulting from the use of with, and recommends
against ever using it
40
Functions
• Functions should be defined in the <head> of an
HTML page, to ensure that they are loaded first
• The syntax for defining a function is:
function fxnName(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
fxnName(arg1, …, argN)
• Simple parameters are passed by value, objects are
passed by reference
41
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)
• [Link](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
42
Warnings
• JavaScript is a big, complex language
We’ve only scratched the surface
It’s easy to get started in JavaScript, but if you need to
use it heavily, plan to invest time in learning it well
Write and test your programs a little bit at a time
• JavaScript is not totally platform independent
Expect different browsers to behave differently
Write and test your programs a little bit at a time
• Browsers aren’t designed to report errors
Don’t expect to get any helpful error messages
Write and test your programs a little bit at a time
43
The for loop (same as C++ )
for (initialization; test; update) {
statements;
}
for (var i = 0; i < 10; i++) {
print(i + "\n");
}
var s1 = "hi, there!!!", s2 = "";
for (var i = 0; i < [Link]; i++) {
var c = [Link](i);
if (c >= "a" && c <= "z") {
s2 += c + c;
}
}
// s2 stores "hhiitthheerree"
44
Logical operators
> < >= <= && || ! == != === !==
• most logical operators automatically convert types:
5 < "7" is true
42 == 42.0 is true
"5.0" == 5 is true
• === , !== are strict equality tests; checks type and value
"5.0" === 5 is false
45
The if/else statement
if (test) {
statements;
} else if (test) {
statements;
} else {
statements;
}
• identical structure to Java's if/else statement...
but JavaScript allows almost any value as a test!
46
Boolean type
var iLike341 = true;
var ieIsGood = "IE6" > 0; // false
if ("JS is great") { ... } // true
if (0 || "") { ... } // false
• any value can be used as a test
"falsey" values: 0, 0.0, NaN, "", null, and undefined
"truthy" values: anything else
• converting a value into a boolean explicitly:
var boolValue = Boolean(otherValue);
var boolValue = !!(otherValue);
47
&& and || in depth
• a && b is a binary operator that returns:
if a is truthy, then b, else a
(this turns out to be a truthy/falsey value in the right cases)
• a || b is a binary operator that returns:
if a is truthy, then a, else b
(this turns out to be a truthy/falsey value in the right cases)
• Examples:
0 || 42 || 12 || -1 returns 42 (truthy)
NaN || null || "" returns "" (falsey)
1 + 1 && 6 && 9 returns 9 (truthy)
3 && 4 && null && 5 && 6 returns null
(falsey)
48
null vs. undefined
var ned = null;
var benson = 9;
var caroline;
• at this point in the code:
ned is null
benson is 9
caroline is undefined
• undefined: has not been declared, does not exist
• null: exists, but specifically assigned an empty value
Why does JavaScript have both of these?
49
The while loop (same as C++)
while (test) {
statements;
}
do {
statements;
} while (test);
• break and continue keywords also behave as in Java
50
Functions
function name(paramName, ..., paramName) {
statements;
}
function myFunction(name) {
print("Hello, " + name + "!\n");
print("How are you?\n");
}
unlike in Java, functions are first-class (can be stored as
variables, passed as parameters, returned, ...)
51
JavaScript keywords
break case catch continue debugger
default delete do else finally
for function if in
instanceof
new return switch this throw
try typeof var void while
with const let export
• Reserved words (these don't do anything yet):
class enum extends import implements
interface package private protected public
static super yield
52
DOM
• Document Object Model is a the Structured
Representation of HTML Documents
• DOM allows JavaScript to Access HTML Element and
Styles to Manipulate them
To Change Text
To Change HTML Attributes
To Change CSS styles
• The DOM is a connection point between HTML
documents and JavaScript Code
• The DOM is automatically Created by the Browser when
the HTML page Loads
53
DOM Structure
54
Selecting Nodes / Elements
Method Description
Selects an individual element within a document using a
getElementById()
specific id
Uses CSS selector to select the first matching element
querySelector()
within a document
Allows you to select all elements with a given class
getElementsByClassName()
attribute
getElementsByTagName() Locates all elements that match a given tag name
querySelectorAll() Uses CSS selector to select one or more elements
55
Traversing the DOM
• The process of selecting another element based on its
relationship to a previously selected element.
Property Description
parentNode Locates the parent element of an initial selection
previousSibling Finds the previous sibling of a selected element
nextSibling Finds the next sibling of a selected element
firstChild Finds the first child of a selected element
• [Link](‘.className’).parentNode
56
Events
Event Description
When a button (usually a mouse button) is pressed and released on a
'click'
single element.
'keydown' When the user first presses a key on the keyboard.
'keyup' When the user releases a key on the keyboard.
'focus' When an element has received focus.
'blur' When an element loses focus.
'submit' When the user submits a form.
'load' When the page has finished loading.
'resize' When the browser window has been resized.
'scroll' When the user scrolls up or down on the page.
57