Topic 4 – JavaScript
Introduction to JavaScript
– JS Syntax, datatypes
– Inputs/Outputs
– Basic Control Structures, Arrays
– Objects and Functions
– The DOM
– Events
– JS libraries and Ajax
Language Fundamentals
What is JS?
2
What is JavaScript & What Can It Do?
Client-Side Scripting
3
What is JavaScript & What Can It Do?
JavaScript’s History
• •
JavaScript was introduced by Netscape in their Navigator browser back in 1996
JavaScript that is supported by your browser contains language features
• not included in the current ECMAScript specification and • missing certain language features from that specification
The latest version of ECMAScript is the Ninth Edition (generally referred to as ES9 or ES2018 ).
4
What is JavaScript & What Can It Do?
JavaScript and Web 2.0
• Early JavaScript had only a few common uses:
• 2000s onward saw more sophisticated uses for
JavaScript
• AJAX as both an acronym and a general term
5
Where Does JavaScript Go?
Inline JavaScript
Inline JavaScript refers to the practice of including JavaScript code directly within certain HTML attributes
more info
6
Where Does JavaScript Go?
Embedded JavaScript
Embedded JavaScript refers to the practice of placing JavaScript code within a
7
Where Does JavaScript Go?
External JavaScript
external JavaScript files typically contain function definitions, data definitions, and entire frameworks.
8
Where Does JavaScript Go?
Users without JavaScript
• • • • •
Web crawler
Browser plug-in. Text-based client. Visually disabled client.
The
Variables and Data Types
Variables in JavaScript are dynamically typed
This simplifies variable declarations, since we do not require
the familiar data-type identifiers Instead, we simply use the var keyword
11
Variables and Data Types
Example variable declarations and Assignments
Defines a variable named abc var abc;
Each line of JavaScript should be terminated with a semicolon
var def = 0; A variable named def is defined and initialized to 0
def= 4 ;
def is assigned the value of 4 Notice that whitespace is unimportant
def =
"hello" ;
def is assigned the value of "hello" Notice that a line of JavaScript can span multiple lines
12
Variables and Data Types
Data Types
two basic data types:
• reference types (usually referred to as objects) and
• primitive types
Primitive types represent simple forms of data.
• Boolean, Number, String, ...
13
Variables and Data Types
Reference Types
var abc = 27;
var def = "hello";
variables with primitive types
var foo = [45, 35, 25]; variable with reference type (i.e., array object)
var xyz = def;
var bar = foo;
bar[0] = 200;
Memory representation
these new variables differ in important ways (see below)
changes value of the first element of array
abc
def
xyz
foo bar
27
"hello"
"hello"
Each primitive variable contains the value directly within the memory for that variable.
memory for foo object instance
45
This element will get changed to
the value of 200. Thus both foo[0] and bar[0] will have the same value (200).
35
25
Each reference variable contains a reference (or pointer) to the memory that contains the contents of that object.
14
Inputs/Outputs
15
JavaScript Output
• alert() Displays content within a pop-up box.
• console.log() Displays content in the Browser’s
JavaScript console.
• document.write() Outputs the content (as markup) directly to the HTML document.
16
JavaScript Output
Chrome JavaScript Console
Web page content
JavaScript console
Output from
console.log()
expressions
Using console interactively to query value of JavaScript variables
17
Language Constructs
Conditionals, Loops, Arrays
18
Conditionals
If, else if, else
if (hourOfDay > 4 && hourOfDay < 12) { greeting = "Good Morning";
}
else if (hourOfDay >= 12 && hourOfDay < 18) {
greeting = "Good Afternoon";
}
else {
}
greeting = "Good Evening";
19
Conditionals
Conditional Assignment
20
Conditionals
Truthy and Falsy
In JavaScript, a value is said to be truthy if it translates to true, while a value is said to be falsy if it translates to false.
• Almost all values in JavaScript are truthy
• false, null, "", '', 0, NaN, and undefined are falsy
21
Loops
While and do . . . while Loops
var count = 0;
while (count < 10) { // do something
// ...
count++;
count = 0;
do {
}
// do something
// ...
count++;
} while (count < 10);
22
Loops
For Loops
initialization condition post-loop operation for (var i = 0; i < 10; i++) {
}
// do something with i
// ...
23
Arrays
Arrays are one of the most commonly used data structures in programming.
JavaScript provides two main ways to define an array. • object literal notation
• use the Array() constructor
24
Arrays
object literal notation
The literal notation approach is generally preferred since it involves less typing, is more readable, and executes a little bit quicker
var years = [1855, 1648, 1420];
var countries = ["Canada", "France",
"Germany", "Nigeria",
"Thailand", "United States"]; var mess = [53, "Canada", true, 1420];
25
Arrays
Some common features
• arrays in JavaScript are zero indexed
• [] notation for access
• .length gives the length of the array
• .push()
• .pop()
• concat(), slice(), join(), reverse(), shift(), and sort()
26
Arrays
Arrays Illustrated
years
Variable
month
0 1 2 3
Indexes
Values
month[0][3]
month[3][2]
0
1
2
1855
1648
1420
0|1|2|3|4
Mon | Tue | Wed | Thu | Fri
0|1|2|3|4
Mon | Tue | Wed | Thu | Fri
0|1|2|3|4
Mon | Tue | Wed | Thu | Fri
0|1|2|3|4
Mon | Tue | Wed | Thu | Fri
27
Objects and Functions
28
Objects
Object Creation and Access—Object Literal Notation
var objName = {
name1: value1,
name2: value2,
// ...
nameN: valueN
};
Access using either of: • objName.name1
• objName["name1"]
29
Objects
Object Creation—Constructed Form
// first create an empty object
var objName = new Object();
// then define properties for this object objName.name1 = value1;
objName.name2 = value2;
30
Functions
Function Declarations vs. Function Expressions
Functions are the building block for modular code in JavaScript.
function subtotal(price,quantity) { return price * quantity;
}
The above is formally called a function declaration, called or invoked by using the () operator
var result = subtotal(10,2);
31
Functions
Function Declarations vs. Function Expressions
// defines a function using a function expression
var sub = function subtotal(price,quantity) { return price * quantity;
};
// invokes the function
var result = sub(10,2);
It is conventional to leave out the function name in function expressions
32
Functions
Anonymous Function Expressions
// defines a function using an anonymous function expression
var calculateSubtotal = function (price,quantity) { return price * quantity;
};
// invokes the function
var result = calculateSubtotal(10,2);
33
Functions
Nested Functions
function calculateTotal(price,quantity) {
var subtotal = price * quantity;
return subtotal + calculateTax(subtotal); // this function is nested
function calculateTax(subtotal) {
}
}
var taxRate = 0.05;
var tax = subtotal * taxRate; return tax;
34
Functions
Hoisting in JavaScript
35
Functions
Callback Functions
36
Functions
Callback Functions
var temp = calculateTotal( 50, 2,
);
Passing an anonymous function definition as a callback function parameter
function (subtotal) {
var taxRate = 0.05;
var tax = subtotal * taxRate;
return tax;
}
37
Functions
Objects and Functions Together
38
Functions
Scope in JavaScript
Each function is like a box with a one-way window
Within any function, it can see out at the content of all its outer boxes
But an outer function can’t look into an inner function
And functions can’t see into other functions at the same level
All functions can see anything within global scope
Scope ends at global ... functions can’t see outside of the global box
39
Functions
Scope in JavaScript
global variable c is defined global function outer() is called
local (outer) variable a is accessed local (inner) variable b is defined global variable c is changed
local (outer) variable a is defined local function inner() is called global variable c is accessed undefined variable b is accessed
Anything declared inside this block is global and accessible everywhere in this block
1 var c = 0;
2 outer();
Anything declared inside this block is accessible everywhere within this block
3 4 8 9
function outer() {
var a = 5;
inner();
console.log(c);
console.log(b);
allowed
not allowed
generates error or outputs undefined
Anything declared inside this block is accessible only in this block
5 6 7
function inner() {
console.log(a);
allowed
outputs 5
}
}
var b = 23;
c = 37;
allowed
outputs 37
40
Functions
Scope in JavaScript
Remember that scope is determined at design-time
var myGlobal = 55;
function outer() { var foo = 66;
function middle() { var bar = 77;
} 2 then looks within first containing function
function inner() {
var foo = 88;
bar = foo + myGlobal;
} 1 looks first within current function
} 3 then looks within next containing function
4 then finally looks within global scope
41
Functions
Function Constructors
1 A brand new empty object is created and given the name cust
var cust = new Customer("Sue", "123 Somewhere", "Calgary");
3
The new empty object is set as the context for this. Thus, the new empty object gains these property values.
function Customer(name,address,city) {
this.name = name;
this.address = address;
this.city = city;
}
2 Then the function is called
4 Sincethereisnoreturn,thefunctionwillendwiththe
(no longer empty) new object being assigned to the cust variable
Note: it is a coding convention to capitalize the first letter of a constructor function
42
Object Prototypes
There’s a better way
While the constructor function is simple to use, it can be an inefficient approach for objects that contain methods.
Prototypes are an essential syntax mechanism in JavaScript, and are used to make JavaScript behave more like an object-oriented language.
43
Object Prototypes
Methods get duplicated...
x1 : Die
this.color = "red"; this.faces = [1,2,3,4,5,6];
this.randomRoll = function() { var randNum = ...;
return faces[randNum-1];
};
x2 : Die
this.color = "green"; this.faces = [1,2,3,4,5,6];
this.randomRoll = function() { var randNum = ...;
return faces[randNum-1];
};
var randNum = ...;
this.color = "blue"; this.faces = [1,2,3,4,5,6];
A function expression is an object whose content is the definition of the function ...
so each instance will contain that same content ...
...
x100 : Die
this.color = "blue"; this.faces = [1,2,3,4,5,6];
this.randomRoll = function() { var randNum = ...;
return faces[randNum-1];
};
Execution memory space
which is incredibly memory inefficient
when there are many instances of that object
44
Object Prototypes
Using Prototypes reduces duplication at run time.
x1 : Die
this.color = "red"; this.faces = [1,2,3,4,5,6]; this.randomRoll
Die.prototype
randomRoll = function() { var randNum = ...; return faces[randNum-1];
};
this.color = "red"; this.faces = [1,2,3,4,5,6]; this.randomRoll
Execution memory space
x2: Die
x100: Die
...
Now only a single copy of the randomRoll() function exists in memory
this.color = "red"; this.faces = [1,2,3,4,5,6]; this.randomRoll
45
Object Prototypes
Using Prototypes to Extend Other Objects
String.prototype.countChars = function (c) { var count = 0;
for (var i = 0; i < this.length; i++) {
if (this.charAt(i) == c)
count++;
}
return count;
}
var msg = "Hello World";
console.log(msg + "has" + msg.countChars("l") + " letter l's");
46