CT219H – Web Programming Fundamentals
Chapter 3
JavaScript
2019
Tran Cong An
(tcan@[Link])
Content
1. Introduction
2. Using JavaScript in an HTML documents
3. JS language basics
4. JS functions
5. DOM
6. OOP in JS
7. Appendix
2
Introduction to JavaScript
3
Introduction to JS
What is JavaScript?
- JS is a programming language (no relation to Java, it is named just for
marketing reason !)
- Currently is the only programming language for browsers
- History:
• Originally developed by Brendan Eich at Netscape (named
LiveScript at that time)
• Became a joint venture of Netscape and Sun in 1995 (renamed
JavaScript)
• Now standardized by the ECMA (ECMA-262, also ISO 16262)
4
Introduction to JS
Why JavaScript?
+ produces
Describes the content Describes the A web page... that doesn't
and structure of the appearance and do anything, except:
page style of the page • Shows the information
• Links to other webpages
- If we want dynamic, more friendly and interactive webpages
(automation, animation, interactivity, etc.)
JavaScript comes to help!
5
Introduction to JS
What JS Can Do?
- User interaction through form are easy
- Document Object Model (DOM) makes it possible to create
dynamic HTML with JS:
• can change the HTML page content
• can show/hide HTML page elements
• can change the HTML element’s attributes
• etc.
- And much more features that we can do with event-driven
computation…
6
Introduction to JS
Basic Features of JS
- An interpreter language (no compilation by developers, it is compiled and
executed on-the-fly by browser)
- Dynamic typed (no need to declare variables, auto type-casting)
- Supports the OO approach (but lack of some basic features of OO such as
polymorphism)
7
Using JS in HTML Documents
8
Using JS in HTML Documents
Internal JS Code
- JS code can be embedded directly in an HTML page using
<script> tag:
<script>
... JavaScript code ...
</script>
- The may be a number of scripts in an HTML page
- Scripts can be placed in the <head> or in the <body> section
vNote: Placing scripts at the bottom of the <body> element improves the
display speed, because script compilation slows down the display
9
Using JS in HTML Documents
External JS Code
- JS script (code) can also be placed in external files and linked to
HTML pages
- JS script files have the extension .js
- To link a JS script, use the <script> tag with the src attribute:
<script src="<script ULR>"></script>
- External JS script advantages:
• Separate JS code and HTML code (easy to read and maintain)
• JS code can be reused/shared in HTML pages
• Cached JS files can speed-up page load, and much more…
Recommended!
10
Using JS in HTML Documents
External JS Code
- External scripts can be referenced with a full URL (placed in other
sites or the same site) or with a relative path (placed in the same site)
- Example:
<script src="scripts/[Link]"></script>
<script src="[Link]
vNotes:
• External JS scripts cannot contain <script> tags
• The <script> tag can be placed anywhere in the HTML page
• An HTML page can use multiple script files: use multiple <script>
tags to link to multiple script files
11
Using JS in HTML Documents
How Does JS Code Get Loaded?
- If a browser receive an HTML page with a reference to a JS file:
1) It will make a request to the web server for the script file
2) After receiving the script files, it will execute the script file
- JS script execution:
• There is no main function as other programming languages
⇒ The script code is executed from the top to the bottom
• JS functions in the script file are only executed when called
12
Using JS in HTML Documents
Output of JS
- JS can display data in different ways:
• Writing into an HTML element, using innerHTML property
• Writing into HTML page, using [Link]()
(Note: Using [Link]() after an HTML document is loaded, will
delete all existing HTML)
• Writing into an alert box, using [Link]()
• Output to browser console, using [Link]()
(usually used for debugging purpose)
13
Using JS in HTML Documents
Output of JS
- Writing to an HTML element:
<!DOCTYPE html>
<html>
<body>
<h1>Today is: <span id="curdate"></span></h1>
<p>5 + 6 = <span id="calc"></span></p>
<script>
var d = (new Date()).toString().substring(0, 15);
[Link]("curdate").innerHTML = d;
[Link]("calc").innerHTML = 5 + 6;
</script>
</body>
</html>
14
Using JS in HTML Documents
Output of JS
- Writing into an alert box:
<!DOCTYPE html>
<html>
<body>
<h2>JS Output</h2>
<button onclick="alert('Hello!')">Click me to say Hello</button>
</body>
</html>
15
Using JS in HTML Documents
Output of JS
- Output to browser console:
<!DOCTYPE html>
<html>
<body>
<h2>JS to console</h2>
<script>
[Link]('Hello, world!');
</script>
</body>
</html>
16
Using JS in HTML Documents
Output of JS
- Output to browser console (cont.):
for
debugging
1. Right click
3. Choose Console
2. Click Inspect
17
JS Language Basics
Statement, syntax, comment, variable, operators, arithmetic,
etc.
18
JS Language Basics
Statements
- Script/Program = { set of instructions/statement }
- A statement is composed of: values (constant/literals or variable),
operators, expressions, keywords, and comments
- A statement ends with a semicolon ;
- Multiple while-space are ignored (so we can add as much as while-
space for readability)
- A statement can be broken into multiple lines
- A set of statements can be grouped in code block, using {…}
19
JS Language Basics
Comments
- For code readability and maintenance
- Will be ignored by JS (doesn’t interpret and execute)
- Single line comments:
• Start with //
• … to the end of line
- Multiline comments:
• Start with /*
• End with */
- Good practice to use comments as much as possible
20
JS Language Basics
Variables
- Declaration: var <var_name> [ = <expression>];
- Example: var name = 'Jerry', age = 40;
- Datatype is not necessary in the variable declaration
(however, JS does has datatypes: number, boolean, string, object, function, null,
undefined, Array, Object, Date)
- JS variables can also be used without declaration
- Variable naming rules (same as identifier naming rules):
• Names can contain letters, digits, underscores, and dollar signs
• Names must begin with a letter, $ and _
• Names are case sensitive
21
JS Language Basics
Variables
- Declaring a variable without assigning value: the variable will
have the value undefined
var age; // ⇒ age = undefined
- Re-declaring a variable doesn’t erase its value
var myAge = 40;
var myAge; // ⇒ age still = 40
- Get the datatype of a variable: use the typeof operato
• Example: typeof myAge returns a string “number”
- We can declare multiple variables in one statement (using comma
to separate variable names)
22
JS Language Basics
Operators
Assignment
Arithmetic
23
JS Language Basics
Operators
Logical
String
JS also provides bitwise operators such
as & (AND), | (OR), ~ (NOT), etc.
Comparison 24
JS Language Basics
Datatypes
- JS variables don’t have types, but the values do
- Primitive datatypes:
• Boolean: true or false
• Number: everything is double (no integers)
• String: in 'single’ or "double" quotes
• Null: null, a value meaning “this has no value”
• Undefined: undefined, i.e. “the variable has no value assigned”
- Object types: Array, Date, String (wraps the primitive datatype)
25
JS Language Basics
Numbers
- All numbers in JS are real numbers, no integer
- Operators are like C/C++ or Java
- Precedence like C/C++ or Java
- Some special values:
• NaN (not-a-number)
• +Infinity
• -Infinity
- There is a Math class, which provide basic math functions (such
as [Link](), [Link](), etc.)
26
JS Language Basics
Strings
- Object type
- Can be defined with single quote (preferred) or double quote
- Immutable
- No char type: letters are strings with length 1
- Methods: charAt, charCodeAt, fromCharCode, indexOf,
lastIndexOf, replace, split, join, substring,
toLowerCase, toUpperCase
- Property: length
- The only operator: +
27
JS Language Basics
String and Number Conversion
- Converse between string and number:
var count = 10;
var s1 = "" + count; //"10"
var s2 = count + "student"; //"10 student"
var n1 = parseInt("10 student"); //10
var n2 = parseFloat("blablabla"); //NaN
var s = [Link](); //"10"
var n3 = Number(true); //1
var n4 = Number(""); //0
- Get a character in a string at a specified position:
var s = "Hello World";
var firstLetter = s[0]; //"H"
var firstLetter = [Link](0); //"H"
28
JS Language Basics
Boolean
- Literal values: true and false
- Operators: &&, || and !
- Non-boolean values can be used as a boolean value with the
following (implicitly) conversion:
• null, undefined, 0, NaN, '', and "" are evaluated to false
• Everything else is evaluated to true
- We can also explicitly convert an arbitrary value to boolean
using the Boolean() constructor or !! operator
29
JS Language Basics
Boolean
var complete = true;
var age = 40;
var old = age > 60; //false
var boolValue = Boolean("to ambiguous"); //true
var boolValue = !!(""); //false
var username = "...";
if (username) {
// username is defined
}
else {
//username is not defined
}
30
JS Language Basics
Equality
- JavaScript operators == and != are basically broken: they do an
implicit type conversion before the comparison
'' == '0' // false
'' == 0 // true
0 == '0' // true
NaN == NaN // false
[''] == '' // true
false == undefined // false
false == null // false
null == undefined // true
31
JS Language Basics
Equality
- ECMAScript standard added === and !== operators with the
better behavior
'' === '0' // false
'' === 0 // false
0 === '0' // false
NaN == NaN // still weirdly false
[''] === '' // false
false === undefined // false
false === null // false
null === undefined // false
32
JS Language Basics
Null and Undefined
- null is a value representing the absence of a value (similar to
null value in Java and nullptr in C++)
- undefined is the value given to a variable that has not had a
value
- However, we can also set a variable's value to undefined !
33
JS Language Basics
Arrays
- An Object type used to store multiple values in a single
variable
- 0-based indexing
- Mutable
- Can check size via length property
var list = []; // Creates an empty array
//create a pre-filled array
var groceries = ['milk', 'cocoa puffs'];
groceries[1] = 'kix'; //access an element of the array
34
JS Language Basics
Arrays
- An array can be used as a list, queue, stack, etc.
- Basic methods:
• push/pop: add/remove the element at the end, return an element
• shift/unshift: remove/add an element at the head, return an element
• concat: joints two or more arrays, return the jointed array
• splice: add/remove elements from an array, return the array after
adding/removing
• sort/reserve: soft/reverse the order of elements in the array, return
the result after sorted, reserved
• slice: select a part of an array, return the selected part
35
JS Language Basics
Arrays
var a = ["Truc", "Lan"];
[Link](); //a=["Lan", "Truc"]
[Link]("Cuc"); //a=["Lan", "Truc", "Cuc"]
[Link]("Mai"); //a=["Mai", "Lan", "Truc", "Cuc"]
var b = [Link](1, 3);
[Link](2, 1, "Tung", "Dao"); //a=["Mai","Lan","Tung","Dao","Cuc"]
[Link](); //a=["Mai", "Lan", "Tung", "Dao"]
[Link](); //a=["Lan", "Tung", "Dao"]
var i = [Link]("Tung"); //1
36
JS Language Basics
Array Iteration Methods
- Simple for loop (usually combined with the length property)
- for ... of statement
- [Link]():
• calls a callback function once for each array element
• The callback function takes 3 parameters: item value, the index
and the array itself
let iterable = [10, 20, 30]; let iterable = [10, 20, 30];
for (const value of iterable) { for (let value of iterable) {
[Link](value); value += 1;
} [Link](value);
}
37
JS Language Basics
Condition Statements – if/else
- Syntax:
if (condition1) {
//block of code to be executed if condition1 is true
} else if (condition2) {
//block of code to be executed if the condition1 is false and condition2 is true
}
...
else {
//block of code to be executed if the condition1 is false and condition2 is false
}
38
JS Language Basics
Condition Statements – if/else
var d = new Date();
var t = [Link]();
[Link]("<h4>" + d + "</h4>");
[Link]("<h3>");
if (t < 12) {
[Link]("Good morning!"); }
else if (t < 18) {
[Link]("Good afternoon!"); }
else {
[Link]("Good evening!");
}
[Link]("</h3>");
39
JS Language Basics
Condition Statement – switch/case
- Syntax:
switch(expression) {
case x:
//code block to be executed when expression = x
break;
case y:
// code block to be executed when expression = y
break;
...
default:
// code block to be executed when all above cases
}
40
JS Language Basics
Condition Statement – switch/case
var d = new Date();
[Link]("<h4>" + d + "</h4>");
[Link]("<h3>");
switch ([Link]()) {
case 0:
case 6:
[Link]("Have a lovely weekend!");
break;
default:
[Link]("Hace a nice working day!");
}
[Link]("</h3>");
41
JS Language Basics
Loop – for
- Syntax:
for (statement 1; statement 2; statement 3) {
//code block to be executed
}
- Example:
for (var i = 1; i <= 6; i++) {
[Link]("<h" + i + ">");
[Link]("Heading " + i);
[Link]("</h" + i + ">");
}
42
JS Language Basics
Loop – while, do/while
- Syntax:
while (condition) {
// code block to be executed
}
do {
//code block to be executed
} while (condition);
43
JS Language Basics
break statement
- Used to jump out a loop or a switch statement and continue
executing the code after the loop or switch
var count = 0;
while (true) {
count++;
var r = [Link]([Link]() * 10);
[Link](r + " ");
if (r == 5) {
[Link]("<p>Found '5' after "
+ count + " times</p>");
break;
}
}
44
JS Language Basics
continue statement
- The continue statement jumps over an iteration of a loop
- The condition of the loop is checked for a new iteration
for (var i = 0; i <= 10; i++) {
if (i % 2 == 0)
continue;
[Link](i + " ");
}
45
JS Functions
46
JS Functions
Function Declaration
- Syntax:
function func_name(parameters) {
//function body (statements)
}
- A function hasn’t been executed until it is called
- A function call can be made before its declaration (hoisting)
function hello(name) {
[Link]("Hello " + name);
}
hello("Messi");
47
JS Functions
Function Expression
- A JS function can also be defined using an expression
var x = function (a, b) {return a * b};
var z = x(4, 3);
alert(z); //alert “12”
- The above function is actually an anonymous function (no name)
- The function is referenced by the variable and it can be called
using the variable
- This also allow to use the function as a parameter or return
value of a function
48
JS Functions
Function Expression
function sort(lessthan, arr) { //pass function as a parameter
for (i=0; i<[Link]-1; i++) {
for (j=i+1; j<[Link]; j++) {
if (lessthan(arr[j], arr[i]))
swap(arr[i], arr[j]);
}
} function d() {
} function e() {
alert('E’);
}
return e; //returns function e()
}
d()(); //alerts 'E'
49
JS Functions
Function Parameters
- Function parameters (formal parameter) are the names listed in
the function definition
- Function arguments (actual parameter) are the real values passed
to (and received by) the function
- Parameter rules:
• JS function definitions do not specify datatype for parameters
• JS functions don’t check the datatype of the passed arguments
• JS functions do not check the number of arguments received
- The built-in object arguments contains an array of the
arguments
50
JS Functions
Function Parameters
function findMax() {
var i;
var max = -Infinity;
for (i = 0; i < [Link]; i++) {
if (arguments[i] > max) {
max = arguments[i];
}
}
return max;
}
51
JS Functions
Pass-by-Reference & Pass-by-Value
- Objects are pass by reference:
• The change of the object properties are reflected outside the
function
- Arguments are pass by value:
• The function only gets to know the value, not the argument’s
location
• Change to arguments are not reflected outside the function
52
Document Object Model (DOM)
55
Document Object Model (DOM)
What is HTML DOM?
- The DOM is a W3C standard for accessing documents,
including core, XML and HTML DOM
- The HTML DOM is a standard object model and programming
interface for HTML, which defines:
• The HTML elements as objects
• The properties of all HTML elements
• The methods to access all HTML elements
• The events for all HTML elements
HTML DOM: a standard for getting, changing, adding,
or deleting HTML elements
56
Document Object Model (DOM)
HTML DOM Model
- The HTML DOM model is constructed as a tree of objects
- When a web page is loaded, the browser creates a Document
Object Model of the page
57
Document Object Model (DOM)
HTML DOM Model
- The objects in the hierarchical tree are called nodes
- Basic node types:
• Document node (Node.DOCUMENT_NODE): represents the entire
document (the root-node of the DOM tree, children: none)
• Element node (Node.ELEMENT_NODE): represents an element
(children: Element, Text, Comment)
• Text node (Node.TEXT_NODE): represents textual content in an
element or attribute (children: none)
• Attribute node (Node.ATTRIBUTE_NODE): represents an
attribute (children: none)
58
Document Object Model (DOM)
HTML DOM Model
59
Document Object Model (DOM)
HTML DOM Methods
- A method is an action that we can perform on HTML elements
Methods Description
Selecting HMTL element
[Link](id) Find an element by element id
[Link](tag) Find an element by tag name
[Link](class) Find an element by class name
[Link](css selectors) Returns the first child element that
matches the given CSS selector(s)
[Link](css selectors) Returns all elements that matches
the given CSS selector(s)
60
Document Object Model (DOM)
HTML DOM Methods
- A method is an action that we can perform on HTML elements
Methods Description
Adding and Deleting elements
[Link](element) Create an HTML element
[Link](node) Add an HTML element
[Link](node) Remove an HTML element
[Link](new, old) Replace an HTML element
[Link](text) Write into the HTML output stream
61
Document Object Model (DOM)
HTML DOM Properties
- Properties: values (of HTML elements) that we can set or change
- Each type of node has its own set of attributes
.innerText: the text content of the specified node (and all its
descendants)
.innerHTML: the HTML content of the specified node
.nodeValue: the node value of the specified node
.nodeName: the name of the specified node
.parentNode: the parent of the specified node (Node object)
.childNodes: the child nodes (NodeList object)
.attributes: attributes of the specified node (NamedNodeMap obj.)
Full list: [Link]
62
Document Object Model (DOM)
HTML DOM Properties
63
Document Object Model (DOM)
HTML DOM Properties
- nodeName:
• Element node: tag name (e.g. “P”, “IMG”, etc.)
• Attribute node: attribute name (e.g. “src”, ”href”, etc.)
• Text/Document node: “#text”, “#document”
- nodeValue:
• Element node: “undefine”
• Text node: text value of the node
• Attribute node: value of the attribute
- Note: to access a property value, using the syntax
<node>.<attribute_name>
64
Document Object Model (DOM)
Change Element Content and Attribute
<html>
<body>
<p id="par1">Hello World</p>
<p><img id="img1" src="[Link]"/>
<img id="img2" src="[Link]"/>
</p>
<script type="text/javascript">
var p1 = [Link]("par1");
[Link] = "New text";
var m2 = [Link]("img2");
[Link] = "[Link]";
</script>
</body>
</html>
65
Document Object Model (DOM)
Change Element Style
- Syntax: <node>.style.<property> = <value>
<body>
<p id="par1">The first paragraph</p>
<p id="par2">The second paragraph</p>
<script type="text/javascript">
var p1 = [Link]("par1");
[Link] = "x-large";
var p2 = [Link]("par2");
[Link] = "blue";
[Link] = "2px dotted #0000FF";
</script>
</body>
66
Document Object Model (DOM)
Change Element Class
- Syntax: <node>.className = <classname>
<head>
<style>
.blue {color: blue; border: 2px dotted #0000FF;}
.big {font-size: x-large;}
</style>
</head>
<body>
<p id="par1">The first paragraph</p>
<p id="par2">The second paragraph</p>
<script type="text/javascript">
[Link]("par1").className = "big";
[Link]("par2").className = "blue";
</script>
</body>
67
Events
68
Events
HTML Events
- HTML provides event handler attributes to use JS code to
handle the events
<element event='some JS code'>
- Some common HTML events:
• Mouse: onclick, ondblclick, onmousedown, onmousemove,
onmouseover, onmouseout, onmouseup
• Keyboard: onkeypress, onkeyup, onkeydown
• Form: onblur, onchange, onfocus, onsubmit, onselect
• Frame/Object: onload, onresize, onscroll
69
Events
HTML Events
<html>
<head>
<script>
function displayDate(eid) {
var e = [Link](eid);
[Link] = Date();
}
</script>
</head>
<body>
<input type="button" value="Click me!" id="bt1"
onclick="displayDate('demo');"
onmouseover="[Link]='red';" onmouseout="
[Link]='black';"/>
<p id="demo">...</p>
</body>
</html>
70
Events
HTML Events
<script>
function prompttext(getf, inp) {
if (getf && ([Link] == "enter your name")) {
[Link] = "";
[Link] = "black";
}
if (!getf && ([Link] == "")) {
[Link] = "enter your name";
[Link] = "gray";
}
}
</script>
<input id="uname" type="text" style="color:gray;"
value="enter your name" onfocus="prompttext(true, this);"
onblur="prompttext(false, this);"/>
71
Events
DOM Event Listeners
- Each DOM object has the following method for event handling:
addEventListener(event name, function name);
• event name: the string of name of the event to listen to
• function name: the name of the JS function that will be executed
when the event fires (this function gets an Event object as param)
Pros: separate JS code from HTML markup
An event can be handled by multiple functions
- To stop listen to an event use the following function:
removeEventListener(event name, function name);
(the parameters are similar to the addEventListerner())
72
Events
HTML DOM Listeners
<script>
[Link]("myButton").addEventListner("click", validate);
function validate(event) {
alert("You click the object: " + [Link]);
var x = [Link]("fname")[0].value;
if (x == "")
alert("Name must be filled out");
else
alert("Hello: " + x);
}
</script>
<body>
<p> Name <input type="text" name="fname">
<input id="myButton" type="button" value="Click me!">
</p>
</body>
73
OOP in JS
74
OOP in JS
JS Objects
- In JS, almost "everything" is an object, except primitives
• Booleans can be objects (if defined with the new keyword)
• Numbers can be objects (if defined with the new keyword)
• Strings can be objects (if defined with the new keyword)
• Dates are always objects
• Maths are always objects
• Regular expressions are always objects
• Arrays are always objects
• Functions are always objects
• Objects are always objects
75
OOP in JS
JS Objects
- A variable can contain a single value
- JS objects:
• A JS object can contain many named values (properties)
• The values are written in pair as name : value
• An object can also contain methods (actions that the object can
performed)
• A method can be considered as a property that contains a
function definition
76
OOP in JS
Create a JS Object
- Three ways to create an object:
• Define and create a single object, using an object literal
var person = {firstName:"John", lastName:"Doe", age:50,
showInfo: function() {
alert([Link]);
}};
• Define and create a single object, with the keyword new
var person = new Object();
[Link] = "John";
[Link] = 50;
showInfo: function() { alert([Link]); };
77
OOP in JS
Create a JS Object
- Three ways to create an object (cont):
• Define an object constructor function, and then create objects
of the constructed type
function User(uname, pass) {
[Link] = uname; [Link] = pass;
[Link] = function() {
alert([Link] + ":" + [Link]);
} //showInfo()
} //User
var alibaba = new User("alibaba", "vomc");
[Link](); //alert “alibaba:vomc”
• Note: new property cannot be added to an existing object
constructor (i.e. cannot inherit)
78
OOP in JS
Add Object Properties
- To add a property to an object, name the property and give it
a value:
scores = {
peach: 100,
mario: 88,
luigi: 91
};
[Link] = 72;
let name = 'wario';
scores[name] = 102;
[Link](scores);
79
OOP in JS
Remove Object Properties
- To remove a property of an object, use delete:
const scores = {
peach: 100,
mario: 88,
luigi: 91
};
[Link] = 72;
let name = 'wario’;
scores[name] = 102;
delete [Link];
[Link](scores);
80
OOP in JS
Iterate through Object Properties
- Use the for ... in loop (for each property in the object):
for (key in object) {
//do something with object[key]
}
- Example:
for (let name in scores) {
[Link](name + ' got ' + scores[name]);
}
81
OOP in JS
Prototype
- JS is described as a prototype-based language
- Prototype may be considered as a “class” of an object created
by am object constructor function
- A prototype is created for every object constructor function
- It is used to:
• create static (common) properties for objects
• add properties (inherit) to an existing object created by an object
constructor function
82
OOP in JS
Prototype
function Person(first, last) {
[Link] = first;
[Link] = last;
}
var person1 = new Person("John", "Doe");
- To add a method for Person:
[Link] = function() {
alert([Link] + " " + [Link]);
};
var person1 = new Person("John", "Doe");
[Link]();
83
OOP in JS
Prototype
- Add a “static” property for a prototype:
function Person(first, last) {
[Link] = first;
[Link] = last;
[Link]++;
};
[Link] = 0;
var person1 = new Person("John", "Doe");
var person2 = new Person("Doe ", "John");
[Link]("[Link]: " + [Link]);
[Link]("[Link]: " + [Link]);
84
Appendix
85
Appendix
Alert Box
- Used to make sure information comes through to the user
- The user will have to click "OK" to proceed
- Syntax: [window.]alert("sometext");
86
Appendix
Confirm Box
- Used verify that the user accept something or not
- The user will have to click either "OK" or "Cancel" to proceed
• If the user clicks "OK", the box returns true.
• If the user clicks "Cancel", the box returns false
- Syntax: [window.]confirm("sometext");
87
Appendix
Prompt Box
- Used to get an input value from users
- The user will have to click either "OK" or "Cancel" to proceed
• If the user clicks "OK" the box returns the input value.
• If the user clicks "Cancel" the box returns null
- Syntax: [window.]prompt("sometext","defaultText");
88
Appendix
Further Reading
- Methods of JS basic datatypes:
• String: indexOf(), lastIndexOf(), slice(), split(), trim(), etc.
• Number: isFinite(), isInteger(), toString(), etc.
• Math: abs(), min(), max(), sqrt(), round(), random(), etc.
- JS regular expression: [Link]
- JS debugging: [Link]
- JS style guide: [Link]
- JS Browser Object Model (BOM, allows JS to "talk to" the browser):
Window, Screen, Location, History, Navigation, Cookies
89
Question?
Chapter 3 – JavaScript
90