Faculty:
Dr. Narinder Kaur
Seera
Intro to Javascript
UNIT III
Client Side Scripting
CS380
2
Why use client-side
programming?
PHP already allows us to create dynamic web
pages. Why also use client-side scripting?
 client-side scripting (JavaScript) benefits:
 usability: can modify a page without having to
post back to the server (faster UI)
 efficiency: can make small, quick changes to
page without waiting for server
 event-driven: can respond to user actions like
clicks and key presses
3
Why use client-side
programming?
 server-side programming (PHP) benefits:
 security: has access to server's private data;
client can't see source code
 compatibility: not subject to browser
compatibility issues
 power: can write files, open connections to
servers, connect to databases, ...
4
What is Javascript?
 a lightweight programming language
("scripting language")
 used to make web pages interactive
 insert dynamic text into HTML (ex: user name)
 react to events (ex: page load user click)
 get information about a user's computer (ex:
browser type)
 perform calculations on user's computer (ex: form
validation)
5
Javascript vs Java
Javascript is -
 interpreted, not compiled
 more relaxed syntax and rules
 fewer and "looser" data types
 variables don't need to be declared
 errors often silent (few exceptions)
 key construct is the function rather than the
class
 "first-class" functions are used in many situations
 contained within a web page and integrates
6
JavaScript is not 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 vs. PHP
 similarities:
 both are interpreted, not compiled
 both are relaxed about syntax, rules, and
types
 both are case-sensitive
 both have built-in regular expressions for
powerful text processing
8
JavaScript vs. PHP
 Differences:
 JS is more object-oriented: noun.verb(), less
procedural: verb(noun)
 JS focuses on user interfaces and interacting
with a document; PHP is geared toward HTML
output and file/form processing
 JS code runs on the client's browser; PHP
code runs on the web server
9
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
 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
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
 You need semicolons if you put two or more statements on the
same line
 It’s probably a good idea to keep using semicolons
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="myJavaScriptFile.js"></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
Linking to a JavaScript file:
script
 script tag should be placed in HTML page's
head
 script code is stored in a separate .js file
 JS code can be placed directly in the HTML
file's body or head (like CSS)
 but this is bad style (should separate content,
presentation, and behavior
13
<script src="filename" type="text/javascript"></script>
HTML
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
Variables
 Variables are 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)
 The word 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
 variables are declared with the var keyword
(case sensitive)
 types are not specified, but JS does have
types ("loosely typed")
 Number, Boolean, String, Array, Object,
Function, Null, Undefined
 can find out a variable's type by calling typeof
16
var name = expression; JS
var clientName = "Connie Client";
var age = 32;
var weight = 127.4; JS
Number type
 integers and real numbers are the same type
(no int vs. double)
 same operators: + - * / % ++ -- = += -= *= /=
%=
 similar precedence to Java
 many operators auto-convert types: "2" * 3 is 6
17
var enrollment = 99;
var medianGrade = 2.8;
var credits = 5 + 4 + (2 * 3);
JS
Comments (same as Java)
 identical to Java's comment syntax
 recall: 4 comment syntaxes
 HTML: <!-- comment -->
 CSS/JS/PHP: /* comment */
 Java/JS/PHP: // comment
 PHP: # comment
18
// single-line comment
/* multi-line comment */
JS
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
Operators, I
 Because most JavaScript syntax is borrowed from C
(and is therefore just like Java), we won’t spend much
time on it
 Arithmetic operators:
+ - * / % ++ --
 Comparison operators:
< <= == != >= >
 Logical operators:
&& || ! (&& and || are short-circuit
operators)
 Bitwise operators:
& | ^ ~ << >> >>>
 Assignment operators:
+= -= *= /= %= <<= >>= >>>= &= ^= |=
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
– === and !== consider their operands unequal if
they are of different types
 Additional operators (to be discussed):
new typeof void delete
Logical operators
22
 > < >= <= && || ! == != === !==
 most logical operators automatically convert
types:
 5 < "7" is true
 42 == 42.0 is true
 "5.0" == 5 is true
 === and !== are strict equality tests; checks
both type and value
 "5.0" === 5 is false
Boolean type
23
var iLike190M = true;
var ieIsGood = "IE6" > 0; // false
if ("web devevelopment is great") { /* true */ }
if (0) { /* false */ }
JS
 any value can be used as a Boolean
 "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);
Statements, I
 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)
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 { }
if/else statement (same as
Java)
26
if (condition) {
statements;
} else if (condition) {
statements;
} else {
statements;
}
JS
 identical structure to Java's if/else statement
 JavaScript allows almost anything as a
condition
for loop (same as Java)
27
var sum = 0;
for (var i = 0; i < 100; i++) {
sum = sum + i;
} JS
var s1 = "hello";
var s2 = "";
for (var i = 0; i < s.length; i++) {
s2 += s1.charAt(i) + s1.charAt(i);
}
// s2 stores "hheelllloo" JS
while loops (same as Java)
28
while (condition) {
statements;
} JS
 break and continue keywords also behave as
in Java
do {
statements;
} while (condition);
JS
Object literals
 You don’t declare the types of variables in
JavaScript
– Objects are variables too. But objects can
contain many values.
– The values are written as name:value pairs
(name and value separated by a colon).
– { name1 : value1 , ... , nameN : valueN }
 Example: A car is an object.
 A car has properties like weight and color,
and methods like start and stop
Object Definition
 You define (and create) a JavaScript object with
an object literal:
 const person = { firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue" };
 The name:values pairs in JavaScript objects
are called properties:
 You can access object properties in two ways:
objectName.propertyName or
objectName["propertyName"]
30
Three ways to create an
object
 You can use an object literal:
– var course = { number: "CIT597", teacher="Dr. Dave" }
 You can use new to create a “blank” object, and add
fields to it later:
– var course = new Object();
course.number = "CIT597";
course.teacher = "Dr. Dave";
 You can write and use a constructor:
– function Course(n, t) { // best placed in <head>
this.number = n;
this.teacher = t;
}
– var course = new Course("CIT597", "Dr. Dave");
Arrays
32
var name = []; // empty array
var name = [value, value, ..., value]; // pre-filled
name[index] = value; // store element
JS
var ducks = ["Huey", "Dewey", "Louie"];
var stooges = []; // stooges.length is 0
stooges[0] = "Larry"; // stooges.length is 1
stooges[1] = "Moe"; // stooges.length is 2
stooges[4] = "Curly"; // stooges.length is 5
stooges[4] = "Shemp"; // stooges.length is 5
JS
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
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");
The length of an array
 If myArray is an array, its length is given by
myArray.length
 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]
Arrays and objects
 Arrays are objects
• car = {Company: “Hyundai", Name: “Creta" }
– car[“Company”] is the same as car.Company
– car.Name is the same as car[“Name“]
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
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) {
document.write(prop + ": " + course[prop]);
}
 Possible output: teacher: Dr. Dave
number: CIT597
 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 course.teacher
 You must use brackets if the property name is in a variable
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 (document.myForm) {
result.value = compute(myInput.value) ;
}
– document.myForm.result.value =
compute(document.myForm.myInput.value);
 One of my books hints at mysterious
problems resulting from the use of with, and
recommends against ever using it
Event-driven programming
40
 split breaks apart a string into an array using a
delimiter
 can also be used with regular expressions (seen
later)
 join merges an array into a single string,
placing a delimiter between them
 A JavaScript can be executed when an event
occurs, like when a user clicks on an HTML
element.
 Examples of HTML events:
 When a user clicks the mouse
 When a web page has loaded
 When an image has been loaded
 When the mouse moves over an element
 When an input field is changed
 When an HTML form is submitted
 When a user strokes a key
41
Event-driven programming
Event-driven programming
42
 you are used to programs start with a main
method (or implicit main like in PHP)
 JavaScript programs instead wait for user
actions called events and respond to them
 event-driven programming: writing programs
driven by user events
 Let's write a page with a clickable button that
pops up a "Hello, World" window...
Buttons
 button's text appears inside tag; can also
contain images
 To make a responsive button or other UI
control:
1. choose the control (e.g. button) and event (e.g.
mouse 1. click) of interest
2. write a JavaScript function to run when the
event occurs
3. attach the function to the event on the control
43
<button>Click me!</button> HTML
Event handlers
 JavaScript functions can be set as event
handlers
 when you interact with the element, the function will
execute
 onclick is just one of many event HTML
attributes we'll use
 but popping up an alert window is disruptive and
annoying
44
<element attributes onclick="function();">...
HTML
<button onclick="myFunction();">Click me!</button>
HTML
A JavaScript statement: alert
 a JS command that pops up a dialog box with
a message
45
alert(“Access Denied.");
JS
Popup boxes
46
alert("message"); // message
confirm("message"); // returns true or false
prompt("message"); // returns user input string
JS
JavaScript functions
47
function name() {
statement ;
statement ;
...
statement ;
} JS
 the above could be the contents of example.js
linked to our HTML page
 statements placed into functions can be
evaluated in response to user events
function myFunction() {
alert("Hello!");
alert("How are you?");
} JS
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 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)
Document Object Model (DOM)
 most JS code
manipulates elements on
an HTML page
 we can examine
elements' state
 e.g. see whether a box is
checked
 we can change state
 e.g. insert some new text
into a div
 we can change styles
49
DOM element objects
50
Accessing elements:
document.getElementById
51
var name = document.getElementById("id");
JS
<button onclick="changeText();">Click me!</button>
<span id="output">replace me</span>
<input id="textbox" type="text" /> HTML
function changeText()
{
var span = document.getElementById("output");
var textBox = document.getElementById("textbox");
textbox.style.color = "red";
} JS
Accessing elements:
document.getElementById
52
 document.getElementById returns the DOM
object for an element with a given id
 can change the text inside most elements by
setting the inner HTML property
 can change the text in form controls by setting
the value property
Changing element style:
element.style
53
Attribute Property or style object
color color
padding padding
background-color backgroundColor
border-top-width borderTopWidth
Font size fontSize
Font famiy fontFamily
Math object
54
var rand1to10 = Math.floor(Math.random() * 10 + 1);
var three = Math.floor(Math.PI);
JS
 methods: abs, ceil, cos, floor, log,
max, min, pow, random, round, sin,
sqrt, tan
 properties: E, PI
Special values: null and
undefined
55
var ned = null;
var benson = 9;
// at this point in the code,
// ned is null
// benson's 9
// caroline is undefined
JS
 undefined : has not been declared, does not
exist
 null : exists, but was specifically assigned an
empty or null value
 Why does JavaScript have both of these?
String type
 charAt returns a one-letter String (there is no char
type)
 length property (not a method as in Java)
 Strings can be specified with "" or ''
 concatenation with + :
 1 + 1 is 2, but "1" + 1 is "11"
56
var s = "Connie Client";
var fName = s.substring(0, s.indexOf(" ")); // "Connie"
var len = s.length; // 13
var s2 = 'Melvin Merchant';
JS
String Methods
57
 charAt() Returns the character at a specified index (position)
 concat() Returns two or more joined strings
 indexOf() Returns the index (position) of the first occurrence
of a value in a string
 replace() Searches a string for a value, or a regular
expression, and returns a string where the values are
replaced
 slice() Extracts a part of a string and returns a new string
 substring() Extracts characters from a string, between two
specified indices (positions)
 toLowerCase() Returns a string converted to lowercase
letters
 toUpperCase() Returns a string converted to uppercase
Splitting strings: split and join
58
var s = "the quick brown fox";
var a = s.split(" "); // ["the", "quick", "brown“,"fox"]
a.reverse(); // ["fox", "brown", "quick", "the"]
s = a.join("!"); // "fox!brown!quick!the"
JS
 split breaks apart a string into an array using a
delimiter
 can also be used with regular expressions (seen
later)
 join merges an array into a single string,
placing a delimiter between them

Unit 3-Javascript.pptx

  • 1.
  • 2.
  • 3.
    Why use client-side programming? PHPalready allows us to create dynamic web pages. Why also use client-side scripting?  client-side scripting (JavaScript) benefits:  usability: can modify a page without having to post back to the server (faster UI)  efficiency: can make small, quick changes to page without waiting for server  event-driven: can respond to user actions like clicks and key presses 3
  • 4.
    Why use client-side programming? server-side programming (PHP) benefits:  security: has access to server's private data; client can't see source code  compatibility: not subject to browser compatibility issues  power: can write files, open connections to servers, connect to databases, ... 4
  • 5.
    What is Javascript? a lightweight programming language ("scripting language")  used to make web pages interactive  insert dynamic text into HTML (ex: user name)  react to events (ex: page load user click)  get information about a user's computer (ex: browser type)  perform calculations on user's computer (ex: form validation) 5
  • 6.
    Javascript vs Java Javascriptis -  interpreted, not compiled  more relaxed syntax and rules  fewer and "looser" data types  variables don't need to be declared  errors often silent (few exceptions)  key construct is the function rather than the class  "first-class" functions are used in many situations  contained within a web page and integrates 6
  • 7.
    JavaScript is notJava  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
  • 8.
    JavaScript vs. PHP similarities:  both are interpreted, not compiled  both are relaxed about syntax, rules, and types  both are case-sensitive  both have built-in regular expressions for powerful text processing 8
  • 9.
    JavaScript vs. PHP Differences:  JS is more object-oriented: noun.verb(), less procedural: verb(noun)  JS focuses on user interfaces and interacting with a document; PHP is geared toward HTML output and file/form processing  JS code runs on the client's browser; PHP code runs on the web server 9
  • 10.
    About JavaScript  JavaScriptis not Java, or even related to Java  The original name for JavaScript was “LiveScript”  The name was changed when Java became popular  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
  • 11.
    Using JavaScript ina 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  You need semicolons if you put two or more statements on the same line  It’s probably a good idea to keep using semicolons
  • 12.
    Where to putJavaScript  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="myJavaScriptFile.js"></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
  • 13.
    Linking to aJavaScript file: script  script tag should be placed in HTML page's head  script code is stored in a separate .js file  JS code can be placed directly in the HTML file's body or head (like CSS)  but this is bad style (should separate content, presentation, and behavior 13 <script src="filename" type="text/javascript"></script> HTML
  • 14.
    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
  • 15.
    Variables  Variables aredeclared 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)  The word 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)
  • 16.
    Variables  variables aredeclared with the var keyword (case sensitive)  types are not specified, but JS does have types ("loosely typed")  Number, Boolean, String, Array, Object, Function, Null, Undefined  can find out a variable's type by calling typeof 16 var name = expression; JS var clientName = "Connie Client"; var age = 32; var weight = 127.4; JS
  • 17.
    Number type  integersand real numbers are the same type (no int vs. double)  same operators: + - * / % ++ -- = += -= *= /= %=  similar precedence to Java  many operators auto-convert types: "2" * 3 is 6 17 var enrollment = 99; var medianGrade = 2.8; var credits = 5 + 4 + (2 * 3); JS
  • 18.
    Comments (same asJava)  identical to Java's comment syntax  recall: 4 comment syntaxes  HTML: <!-- comment -->  CSS/JS/PHP: /* comment */  Java/JS/PHP: // comment  PHP: # comment 18 // single-line comment /* multi-line comment */ JS
  • 19.
    Comments  Comments areas 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
  • 20.
    Operators, I  Becausemost JavaScript syntax is borrowed from C (and is therefore just like Java), we won’t spend much time on it  Arithmetic operators: + - * / % ++ --  Comparison operators: < <= == != >= >  Logical operators: && || ! (&& and || are short-circuit operators)  Bitwise operators: & | ^ ~ << >> >>>  Assignment operators: += -= *= /= %= <<= >>= >>>= &= ^= |=
  • 21.
    Operators, II  Stringoperator: +  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 – === and !== consider their operands unequal if they are of different types  Additional operators (to be discussed): new typeof void delete
  • 22.
    Logical operators 22  >< >= <= && || ! == != === !==  most logical operators automatically convert types:  5 < "7" is true  42 == 42.0 is true  "5.0" == 5 is true  === and !== are strict equality tests; checks both type and value  "5.0" === 5 is false
  • 23.
    Boolean type 23 var iLike190M= true; var ieIsGood = "IE6" > 0; // false if ("web devevelopment is great") { /* true */ } if (0) { /* false */ } JS  any value can be used as a Boolean  "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);
  • 24.
    Statements, I  MostJavaScript 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)
  • 25.
    Statements, II  Theswitch statement: switch (expression){ case label : statement; break; case label : statement; break; ... default : statement; }  Other familiar statements: – break; – continue;  The empty statement, as in ;; or { }
  • 26.
    if/else statement (sameas Java) 26 if (condition) { statements; } else if (condition) { statements; } else { statements; } JS  identical structure to Java's if/else statement  JavaScript allows almost anything as a condition
  • 27.
    for loop (sameas Java) 27 var sum = 0; for (var i = 0; i < 100; i++) { sum = sum + i; } JS var s1 = "hello"; var s2 = ""; for (var i = 0; i < s.length; i++) { s2 += s1.charAt(i) + s1.charAt(i); } // s2 stores "hheelllloo" JS
  • 28.
    while loops (sameas Java) 28 while (condition) { statements; } JS  break and continue keywords also behave as in Java do { statements; } while (condition); JS
  • 29.
    Object literals  Youdon’t declare the types of variables in JavaScript – Objects are variables too. But objects can contain many values. – The values are written as name:value pairs (name and value separated by a colon). – { name1 : value1 , ... , nameN : valueN }  Example: A car is an object.  A car has properties like weight and color, and methods like start and stop
  • 30.
    Object Definition  Youdefine (and create) a JavaScript object with an object literal:  const person = { firstName: "John", lastName: "Doe", age: 50, eyeColor: "blue" };  The name:values pairs in JavaScript objects are called properties:  You can access object properties in two ways: objectName.propertyName or objectName["propertyName"] 30
  • 31.
    Three ways tocreate an object  You can use an object literal: – var course = { number: "CIT597", teacher="Dr. Dave" }  You can use new to create a “blank” object, and add fields to it later: – var course = new Object(); course.number = "CIT597"; course.teacher = "Dr. Dave";  You can write and use a constructor: – function Course(n, t) { // best placed in <head> this.number = n; this.teacher = t; } – var course = new Course("CIT597", "Dr. Dave");
  • 32.
    Arrays 32 var name =[]; // empty array var name = [value, value, ..., value]; // pre-filled name[index] = value; // store element JS var ducks = ["Huey", "Dewey", "Louie"]; var stooges = []; // stooges.length is 0 stooges[0] = "Larry"; // stooges.length is 1 stooges[1] = "Moe"; // stooges.length is 2 stooges[4] = "Curly"; // stooges.length is 5 stooges[4] = "Shemp"; // stooges.length is 5 JS
  • 33.
    Array literals  Youdon’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 tocreate 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");
  • 35.
    The length ofan array  If myArray is an array, its length is given by myArray.length  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 = {Company: “Hyundai", Name: “Creta" } – car[“Company”] is the same as car.Company – car.Name is the same as car[“Name“]
  • 37.
    Array functions  IfmyArray 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
  • 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) { document.write(prop + ": " + course[prop]); }  Possible output: teacher: Dr. Dave number: CIT597  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 course.teacher  You must use brackets if the property name is in a variable
  • 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 (document.myForm) { result.value = compute(myInput.value) ; } – document.myForm.result.value = compute(document.myForm.myInput.value);  One of my books hints at mysterious problems resulting from the use of with, and recommends against ever using it
  • 40.
    Event-driven programming 40  splitbreaks apart a string into an array using a delimiter  can also be used with regular expressions (seen later)  join merges an array into a single string, placing a delimiter between them
  • 41.
     A JavaScriptcan be executed when an event occurs, like when a user clicks on an HTML element.  Examples of HTML events:  When a user clicks the mouse  When a web page has loaded  When an image has been loaded  When the mouse moves over an element  When an input field is changed  When an HTML form is submitted  When a user strokes a key 41 Event-driven programming
  • 42.
    Event-driven programming 42  youare used to programs start with a main method (or implicit main like in PHP)  JavaScript programs instead wait for user actions called events and respond to them  event-driven programming: writing programs driven by user events  Let's write a page with a clickable button that pops up a "Hello, World" window...
  • 43.
    Buttons  button's textappears inside tag; can also contain images  To make a responsive button or other UI control: 1. choose the control (e.g. button) and event (e.g. mouse 1. click) of interest 2. write a JavaScript function to run when the event occurs 3. attach the function to the event on the control 43 <button>Click me!</button> HTML
  • 44.
    Event handlers  JavaScriptfunctions can be set as event handlers  when you interact with the element, the function will execute  onclick is just one of many event HTML attributes we'll use  but popping up an alert window is disruptive and annoying 44 <element attributes onclick="function();">... HTML <button onclick="myFunction();">Click me!</button> HTML
  • 45.
    A JavaScript statement:alert  a JS command that pops up a dialog box with a message 45 alert(“Access Denied."); JS
  • 46.
    Popup boxes 46 alert("message"); //message confirm("message"); // returns true or false prompt("message"); // returns user input string JS
  • 47.
    JavaScript functions 47 function name(){ statement ; statement ; ... statement ; } JS  the above could be the contents of example.js linked to our HTML page  statements placed into functions can be evaluated in response to user events function myFunction() { alert("Hello!"); alert("How are you?"); } JS
  • 48.
    Functions  Functions shouldbe defined in the <head> of an HTML page, to ensure that they are loaded first  The 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)
  • 49.
    Document Object Model(DOM)  most JS code manipulates elements on an HTML page  we can examine elements' state  e.g. see whether a box is checked  we can change state  e.g. insert some new text into a div  we can change styles 49
  • 50.
  • 51.
    Accessing elements: document.getElementById 51 var name= document.getElementById("id"); JS <button onclick="changeText();">Click me!</button> <span id="output">replace me</span> <input id="textbox" type="text" /> HTML function changeText() { var span = document.getElementById("output"); var textBox = document.getElementById("textbox"); textbox.style.color = "red"; } JS
  • 52.
    Accessing elements: document.getElementById 52  document.getElementByIdreturns the DOM object for an element with a given id  can change the text inside most elements by setting the inner HTML property  can change the text in form controls by setting the value property
  • 53.
    Changing element style: element.style 53 AttributeProperty or style object color color padding padding background-color backgroundColor border-top-width borderTopWidth Font size fontSize Font famiy fontFamily
  • 54.
    Math object 54 var rand1to10= Math.floor(Math.random() * 10 + 1); var three = Math.floor(Math.PI); JS  methods: abs, ceil, cos, floor, log, max, min, pow, random, round, sin, sqrt, tan  properties: E, PI
  • 55.
    Special values: nulland undefined 55 var ned = null; var benson = 9; // at this point in the code, // ned is null // benson's 9 // caroline is undefined JS  undefined : has not been declared, does not exist  null : exists, but was specifically assigned an empty or null value  Why does JavaScript have both of these?
  • 56.
    String type  charAtreturns a one-letter String (there is no char type)  length property (not a method as in Java)  Strings can be specified with "" or ''  concatenation with + :  1 + 1 is 2, but "1" + 1 is "11" 56 var s = "Connie Client"; var fName = s.substring(0, s.indexOf(" ")); // "Connie" var len = s.length; // 13 var s2 = 'Melvin Merchant'; JS
  • 57.
    String Methods 57  charAt()Returns the character at a specified index (position)  concat() Returns two or more joined strings  indexOf() Returns the index (position) of the first occurrence of a value in a string  replace() Searches a string for a value, or a regular expression, and returns a string where the values are replaced  slice() Extracts a part of a string and returns a new string  substring() Extracts characters from a string, between two specified indices (positions)  toLowerCase() Returns a string converted to lowercase letters  toUpperCase() Returns a string converted to uppercase
  • 58.
    Splitting strings: splitand join 58 var s = "the quick brown fox"; var a = s.split(" "); // ["the", "quick", "brown“,"fox"] a.reverse(); // ["fox", "brown", "quick", "the"] s = a.join("!"); // "fox!brown!quick!the" JS  split breaks apart a string into an array using a delimiter  can also be used with regular expressions (seen later)  join merges an array into a single string, placing a delimiter between them

Editor's Notes

  • #3 client-side script: code runs in browser after page is sent back from server often this code manipulates the page or responds to user actions
  • #33 two ways to initialize an array length property (grows as needed when elements are added)
  • #44 Reset is not working here! Debug! test1.html
  • #51 every element on the page has a corresponding DOM object access/modify the attributes of the DOM object with objectName.attributeName
  • #52 span.innerHTML = textBox.value;