KTLT 2-6

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 142

HTML DOM

1
DOM (Document Object Model)

• Document Object Model of the page = a tree of Objects


https://www.w3schools.com

HTML DOM Tree of Objects

parentNode, childNodes[nodenumber], firstChild, lastChild, nextSibling, etc.

2
HTML DOM

• How to get, change, add, or delete HTML elements ?


• HTML DOM: standard model for HTML documents
• HTML elements as objects
• properties of all elements
• methods to access all elements
• events for all elements
• HTML DOM can be accessed with JavaScript (and with other
programming languages)
<script>
document.getElementById("demo").innerHTML = "Hello World!";
</script>

method property

3
HTML DOM

Method Description
document.getElementById(id) Find an element by element id
document.getElementsByTagName(name) Find elements by tag name
document.getElementsByClassName(name) Find elements by class name
document.createElement(element) Create an HTML element
document.removeChild(element) Remove an HTML element
document.appendChild(element) Add an HTML element
document.replaceChild(new, old) Replace an HTML element
document.write(text) Write into the HTML output stream
document.getElementById(id).onclick =
Adding event handler code to an onclick event
function(){code}

Property Description
element.innerHTML = new html content Change the inner HTML of an element
element.attribute = new value Change the attribute value of an HTML element
element.style.property = new style Change the style of an HTML element

element.setAttribute(attribute, value) Change the attribute value of an HTML element

https://www.w3schools.com 4
Using HTML DOM with JavaScript

• Modify HTML Content


<html>
<body>
<p id="p1">Hello World!</p>
<script>
document.getElementById("p1").innerHTML = “Hi !";
</script>
</body>
</html>

<script>
const element = document.getElementById(“p1");
element.innerHTML = “Hi !";
</script>

5
Using HTML DOM with JavaScript

• Modify value of attribute


<html>
<body>
<img id=“img1" src=“image.gif">
<script>
document.getElementById(“img1").src = “new_image.jpg";
</script>
</body>
</html>

6
Using HTML DOM with JavaScript

• Create dynamic HTML content


<html>
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = “dynamic content”;
</script>
</body>
</html>

• Write into the HTML output <html>


<body>
<p>abc</p>
<script>
document.write(‘some content’);
</script>
<p>def</p>
</body>
</html>
7
Using HTML DOM with JavaScript

• Validate input
<input id="number">
<button type="button" onclick="myFunction()">Submit</button>
<p id="demo"></p>

<script>
function myFunction() {
let x = document.getElementById("number").value;
let text;
if (isNaN(x) || x < 1 || x > 10) {
text = "Input not valid";
} else {
text = "Input OK";
}
document.getElementById("demo").innerHTML = text;
}
</script>

8
Using HTML DOM with JavaScript

• Form Validation
<script>
function validateForm() {
let x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name can not be empty");
return false;
}
}
</script>
....
<form name="myForm" action="/action.php" onsubmit="return validateForm()"
method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>

9
Using HTML DOM with JavaScript

• Create HTML animations


<script>
function myMove() {
let id = null;
const elem = document.getElementById("animate");
let pos = 0;
clearInterval(id);
id = setInterval(frame, 5);
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + "px";
elem.style.left = pos + "px";
}
}
}
</script>

10
Using HTML DOM with JavaScript

• React to HTML events


• HTML events: clicks the mouse, web page/image has loaded, mouse moves over an
element, input field is changed, form is submitted, strokes a key, etc.
<!DOCTYPE html>
<html>
<body>
<h1 onclick="changeText(this)">Click here!</h1>
<script>
function changeText(id) {
id.innerHTML = “You are clicked!";
}
</script>
</body>
</html>

<button onclick=“....“> .... </button>


// in script
document.getElementById(“id").onclick = func;
document.getElementById(“id").addEventListener("click", func);
11
• Some Demonstrations !

12
Other extensions
Browser Object Model

• Window Object
• window.open() - open a new window
• window.close() - close the current window
• window.moveTo() - move the current window
• window.resizeTo() - resize the current window
• window.screen
• window.location
• window.history
• window.navigator
• window.prompt(), window.confirm(), window.alert()
• Timing
• Cookies

14
Asynchronous JavaScript And XML

• AJAX
• Read data from a web server - after the page has loaded
• Update a web page without reloading the page
• Send data to a web server - in the background
• not a programming language
• a combination of:
• A browser built-in XMLHttpRequest object (to request data from a web server)
• JavaScript and HTML DOM (to display or use the data)

https://www.w3schools.com/js/js_ajax_intro.asp

15
JSON

• JavaScript Object Notation


• a text format for storing and transporting data
• plain text written in JavaScript object notation
• JSON is used to send data between computers

16
JavaScript / jQuery DOM Selectors

• to simplify HTML DOM Manipulation, Event Handling, Animations, and Ajax.

myElement = document.getElementById("id01"); //javaScript


myElement = $("#id01"); // jQuery

17
Chapter 3: Variables and Data Types

1
Content

1. Variables
2. Basic data types
3. String
4. Array
5. Object
6. Other techniques

2
1. Variables

3
Variable concept

• like a box in memory containing a


value for a certain quantity
• The variable name does not change Variable value
• Variables can contain numeric, character,
text, or object value type
Variable name
• The variable is assigned a value of this
type (which can be changed during
runtime)

4
Variable concept

• Name – Type – Value


• Name:
• indicate the variable in program
• where is the box in the memory (address) Variable value

• Type:
• what can be stored in the box
Variable name
• normally unchanged after setting
• size of the box, type of the box
• Value:
• value of each bit in the box (0,1)
• corresponding to value of the variable

5
Working with variable

• Variables before used must be declared by a name (identifier), a


type (number, character, text, or object, etc.) and assigned to a
value
• Declaration statement
• Assignment statement
• After, access to the memory area associated with the variable using
the variable name
• and change the value

6
Working with variable in JavaScript

• Declaration a variable
let mes = ‘hello’;

const mes = ‘HELLO’;


// unchanged

In old scripts:
var message = 'Hi';

• JavaScript is “dynamically typed”, or “type less”


• No way to declare a variable type
• The value decides the type of variable
• A variable can have different values, of different type in one program

7
Working with variable in JavaScript

• Combine declaration and initialization


let mes = ‘hello’;

• declare multiple variables


let mes = ‘hello’, x = 23, a = 34.5;

let mes = ‘hello’;


let x = 23;
let a = 34.5;

let mes = ‘hello’,


x = 23,
a = 34.5;

let mes = ‘hello’


, x = 23
, a = 34.5;

8
Working with variable in JavaScript

• A repeated declaration of the same variable is an error


• Use the variable
let mes = ‘hello’;
mes = 23.4;
alert(mes);

• Change the value


let message; let hello = 'Hello world!';
message = 'Hello!';
message = 'World!';
message = hello;

9
Identifier Concept

• Identifier :
• tokens that represent names of variables, constants, methods, objects,
classes, files
• unique in the program

• Regulations for valid identifier in JavaScript:


• Includes characters that can be letters, digits, or '$' or '_'
• Not allowed to :
• Start with a digit
• Match the keyword, reserved words
• Contains spaces
• Case-sensitive
• Yourname, yourname, YourName and yourName are 4 different identifiers
• Non-Latin letters are allowed, but not recommended

10
Identifier Concept (2)

• Naming convention:
• Must be reminiscent
• For example, the identifier "bookPrice" rather than "bp" should be
used to store information about the price of a book
• Start with letters
• For Class: capitalize the first letter of each word
• TheExample
• For method/field: Start with a lowercase letter, capitalize the first letter
of the remaining words
• theExample
• For constants:
• value of the variable can’t be changed
• Naming in all capitalization

const COLOR = ‘#FF7F00’;


let your_choice = COLOR;

11
JavaScript Keywords

• Not allowed to use as an identifier


abstract arguments boolean break
byte case catch char
const continue debugger default
delete do double else
eval false final finally
float for function goto
if implements in instanceof
int interface let long
native new null package
private protected public return
short static switch synchronized
this throw throws transient
true try typeof var
void volatile while with
yield etc. https://www.w3schools.in/javascript/keywords

12
2. Basic data types in JavaScript

13
Data types in JavaScript

• Data is classified according to different criteria => data type


• Each data type has a defining property and has its own instance
type
• In JavaScript, data types are divided into two types:
• Primitive data type
• Number: (of any kind) integer or floating-point, integers
• bigint: for integer numbers of arbitrary length
• string: of zero or more characters, no separate single-character type
• boolean: for true/false
• null: unknown values
• undefined: unassigned values
• symbol: unique identifiers.
• non-primitive/complex data type
• array
• object

14
Number

• Represents both integer and floating point numbers


• limited by ±(253-1) let x = 2000000000;
• “two Zeros”: +0, -0 let x = 2_000_000_000;

• “Special numeric values”:


• Infinity: ∞ (special value that’s greater than any number)
• -Infinity (smaller than any number)
• NaN (not a number)
• Object wrapper Number
• properties

15
Integer Number

Integer literals
• 10 Decimal
• Octal (0)
032 = 011 010(2) = 16 + 8 + 2 = 26(10)
• Hexadecimal (0x):
0x1A = 0001 1010(2) = 16 + 8 + 2 = 26(10)
• Binary (0b):
0b11111111 = 255 (10)
• Exponent (e):
5e2  500
5e-2  0.05
0.5e2  50

16
Number

• Number() convert variables to numbers


Number(" 10") //  10 Number("10,33") //  NaN

• num.toString(); num.toString(base)
• returns a string representing the specified number value
• in the decimal or the given base numeral system
let num = 255;
num.toString(16) // ”FF”
num.toString(2) // ”11111111”
255..toString(16) // ”FF” -- Two dots
(255).toString(16) // ”FF” -- or parenthesis , etc.

• parseInt() and parseFloat()


parseInt('125px') // 125
parseFloat('12.5em') // 12.5

parseInt('13.4') // 13
parseFloat('13.4.5') // 13.4

17
NaN - Number.NaN

• Value representing Not-A-Number:


• Failed number conversion:
parseInt(“abc"), Number(undefined), Math.abs(undefined))
• Not a real number result from Math operation:
Math.sqrt(-1)
• Indeterminate form:
0 * Infinity
• A method or expression whose operand is NaN
7 * “abc”
• Where an invalid value is to be represented as a number
new Date(“abc").getTime()

• When NaN is one of the operands of any relational comparison (>, <, >=, <=), the
result is always false
• NaN compares unequal to any other value — including to another NaN value

18
NaN - Number.NaN

• isNaN(value)
• return true if the value is currently NaN, or after converting the value to a
number, the result is NaN
isNaN("hello world"); // true
isNaN("NaN"); // true
isNaN(true); // false (1)
isNaN("37"); // false (37)
isNaN(""); // false (0)

• Number.isNaN(value)
• return true only if the value is currently NaN
• non-numbers always return false
Number.isNaN("hello world"); // false
Number.isNaN(0 / 0); // true
Number.isNaN(NaN); // true

19
Infinity

• Numeric value representing infinity


• Infinity: Number.POSITIVE_INFINITY
- Infinity: Number.NEGATIVE_INFINITY

console.log(Infinity ); /* Infinity */
console.log(Infinity + 1 ); /* Infinity */
console.log(Math.pow(10, 1000)); /* Infinity */
console.log(Math.log(0) ); /* -Infinity */
console.log(1 / Infinity ); /* 0 */
console.log(1 / 0 ); /* Infinity */

20
Infinity

• isFinite(value)
• converts value to a number (if needed)
• return true if the result is not NaN/Infinity/-Infinity/undefined
• Number.isFinite(value)
• checks whether value belongs to the number type, and not being
NaN/Infinity/-Infinity
• return true if the given value is a finite number.

Number.isFinite(Infinity); // false isFinite('0'); // true (0)


Number.isFinite(NaN); // false Number.isFinite("0"); // false
Number.isFinite(-Infinity); // false isFinite(null); // true (0)
Number.isFinite(null); // false
Number.isFinite(10); // true
Number.isFinite(1e6); // true

21
BigInt

• represent integers of arbitrary length


• A BigInt value is created by appending n to the end of an integer
const bigVar = 1234567890123456789012345678901234567890n
• BigInt is rarely needed

22
The “null” value

• special type in JavaScript


• contains only the null value
• is not only a “reference to a non-existing object” or a “null pointer”
• It’s a special value which represents “nothing”, “empty” or “unknown”.
• often retrieved in a place where an object can be expected but no object is
relevant

function hasVowels(str) {
const m = str.match(/[aeiou]/gi);
if (m === null) {
return 0;
}
return 1;
}

23
The “undefined” value

• special type in JavaScript


• A variable that has not been assigned a value is of type undefined

let mess;
alert(mess); // undefined

• reserved as a default initial value for unassigned things

24
Boolean (logical type)

• boolean type has only two values: true and false


let isChecked = true;

• What is false:
• false (boolean), 0 (number), -0 (number), 0n (BigInt), “” (empty string)
• null, undefined, NaN

25
Symbol

• a symbol is a “primitive unique value” with an optional description


• Created using Symbol()
let myid = Symbol(); // a new symbol
let myid = Symbol("id"); // a new symbol myid with the description “id”
• Symbols are guaranteed to be unique
let myid1 = Symbol("id");
let myid2 = Symbol("id"); // false
• Symbol is rarely used.

26
typeof operator

• returns the type of the argument

typeof undefined // undefined


typeof 0 // number
typeof 10n // bigint
typeof true // boolean
typeof "foo" // string
typeof null // object
typeof NaN // number
typeof Infinity // number

27
3. String in JavaScript

• String type is used to store a string of characters: a collection of


many readable characters.
• in JavaScript, no separate type for a single character
let str1 = 'first string';
let str2 = "second string";
let str3 = `third string`;

let str = 'written \ // might not have universal support


over \
multiple \
lines';

• Backticks: embed any expression into string, by wrapping in ${…}


let name = "John";
let a = `Hello, ${name}!`; // Hello, John!
let b = `x is ${1 + 2}`; // x is 3

28
String

• Control keys
• \b backspace
• \f form feed
• \n newline
• \r return (go to beginning of line)
• \t tab
• Special characters in strings
• \" quotation mark
• \’ apostrophe
• \\ backslash
• \0: NUL character
• \xHH: specifies a character via an ASCII code
• \uHHHH: specifies a character via an UTF-16 code

29
Working with string

• concatenation strings : 3 + ‘times’  ‘3 times’

• get string length: `My\n`.length // 3

• access characters: let str = `Hello`;


str[0] // H
str.at(0) // H
str[str.length - 1] // o
str.at(-1) // o
str[-2] // undefined

• string can’t be changed


let str = 'Hi';
str[0] = 'h'; // error

30
Working with string

• Extracting a part of a string:


• charAt(pos)
• charCodeAt(pos)
• slice(start_pos [, end_pos])
• substring(start_pos [, end_pos]) // pos can not be negative
• substr(start_pos, length)
• Replacing String Content:
• replace(old_str, new_str)
• Other methods:
• toLowerCase(), toUpperCase()
• indexOf(substr, pos)
• lastIndexOf(substr, pos)
• trim()
• etc.

31
4. Arrays in JavaScript

• To store ordered collections of values (1st, a 2nd, a 3rd element and so


on)
• in the contiguous memory area, one after another
• Declaration:
• let arr = new Array()
• let arr = [] // => most of the time
• let fruits = [“Apple”, “Orange”, “Plum”]

32
4. Arrays in JavaScript

• Accessing array elements:


• Array elements are indexed, starting with zero
• access to elements by index
fruits[0] // Apple
or .at()
fruits.at(-1) // Plum

• element looks like a single variable, can change the value


const cars = [];
cars[0]= "Saab";
cars[1]= "Volvo";
cars[2]= "BMW";
let car = cars[0];

33
Arrays

• In JavaScript:
• can add a new element to the array (extend the array)
let fruits = ["Apple", "Orange", "Pear"];
fruits[3] = 'Lemon'; // now ["Apple", "Orange", "Pear", "Lemon"]

• count of the elements in the array: fruits.length


• updated when the array is modified
• = the greatest numeric index plus one

• an array can store elements of any type


let mixedArr = [“Hello”, “World”, 1, false]

• array can be used as if it were a regular object, but not recommended

34
Working with array

• toString(), sort(), reverse()


• splice(start[, deleteCount, elem1, ..., elemN]): insert,
remove and replace elements
• slice([start], [end]): returns a new array from current array by
copying all items from index start to end (not including end)
• concat(arg1, arg2...): append to the current array the values
from arg1, arg2, etc.
• indexOf(item, from), .lastIndexOf
• includes(item, from)
• etc.

35
Working with array

• Arrays in JavaScript can work both as a queue and as a stack.


• .pop(): returns the last element of the array and removes it from array
• .push(element): append element to the end of the array
• .shift(): returns the first element of the array and removes it from
array
• .unshift(element): add element to the beginning of the array

• push and unshift can add multiple elements at once

36
Working with array

• Split
let names = ‘Peter, James, Mary’;
let arr = names.split(', ');
// arr = [‘Peter', ‘James', ‘Mary']

• Split into letters


let str = "test";
str.split('') ; // t,e,s,t

• and join
let arr = ['Peter', ‘James', ‘Mary'];
let str = arr.join(';'); // glue the array into a string using ;
//  str will be ‘Peter;James;Mary’

• etc.
37
5. Objects in JavaScript

• A special type in JavaScript


• Not a primitive type
• Objects: are used to store keyed collections of various data and
more complex entities.
• Object can have list of properties
• A property is a “key-name: value” pair
• key is a string (also called a “property name”), and value can be anything

38
5. Objects in JavaScript

• Declaration:

let user = new Object(); // "object constructor" syntax

let user = {}; // "object literal" syntax, empty object

let user2 = { // an object


name: "John", // key "name" stores value "John"
age: 30 , // key "age" stores value 30
"likes car": true , // multiword property must be quoted
};

39
Object

• How it’s actually stored in memory


• For primitives, store and copy copied “as a whole value”
• while objects are stored and copied “by reference”

let message = "Hello!";


let phrase = message; message "Hello!"

phrase "Hello!"
let user = {
name: "John"
};
user address of
// copy the reference true object
let admin = user; name: “John”

admin address of
the same object

40
Object

• properties can be references to other objects


let user = {
name: "John",
sizes: {
height: 182,
width: 50
}
};

• property can be assigned to a function (see later)


• To access the properties
user.name // John
user.age // 30
user["likes car"] = true;

• see more in Chapter 7: Class and Object

41
6. Other techniques

42
Type Conversions

• String conversion:
• need the string form of a value
• 3 + ‘times’  ‘3 times’
• String(value) function
• .toString() function

• Numeric Conversion:
• in mathematic operator:
• "6" / "2" = 3
• to convert explicitly: use Number(value) function
let num = Number(“364”); // becomes a number 364
alert(typeof num); // number

43
Type Conversions

• Numeric conversion rules:

44
Type Conversions

• Boolean Conversion
• Values like 0, empty string, null, undefined, and NaN  false.
• Other values become true.
• Boolean(value) function

45
Some notes

https://www.w3schools.com/js/js_type_conversion.asp
46
Scope of variables

• The scope of a variable is the program area to which the variable


can be referenced/available.
• The scope of variable allows defining the principles of variable
creation, use, and release of variables.
• Classify:
• Global variable: scope in all program
• Local variable: declared in a method / block and accessible only
in that method / block.

{
let message = "Hello"; // only visible in this block
alert(message); // Hello
}
alert(message); // Error: message is not defined

47
Exercise

• Declare two variables x and y, assign the value “Big X” to x. Copy the
value from x to y. Show the value of y using alert().
• What is the output of the script?
let name = “javaScript";
alert( `hello ${1}` ); // ?
alert( `hello ${"name"}` ); // ?
alert( `hello ${name}` ); // ?

48
Chapter 4: Operators and Expressions

1
Content

1. Operators
• Assignment operator
• Arithmetic operators
• Bit operators
• Relational / comparison operators
• Logical operators
• Other operators
2. Expression

2
1. Operators

3
Operators

• Combine single values ​or sub-expressions into new, more complex


expressions and can return values.
• JavaScript provides the following types of operators:
• Assignment operator: =, +=, -=, *=, /=, %=
• Arithmetic operators: +, -, *, /, %, **, Increment/decrement
• Bitwise operators: &, |, ^, ~, <<, >>, >>>
• Comparison operators: ==, !=, >, <, >=, <=
• Logical operators: &&, ||, !
• Numeric conversion, String concatenation

4
Assignment

• The “=” notation is used to set value for a variable


let a = 1 // 1
a = 100 // 100
• Assignment return a value
let a = 1 // writes the value into a and then returns 1.
alert (a = 100) // 100
• Chaining assignment
let a,b,c
a = b = c= 100 // 100
• Modify-in-place: +=, -=, *=, /=
let a = 10 // 10
a += 90 // same as a = a + 90
Assignment

• For primitive type variables, assignment means copy value


let a = 1, b = a // a = 1, b = 1
a = 100 // a = 100, b = 1

b is a carbon copy of a; b and a have different memory addresses!


• For object type variables, assignment means copy reference
let obj1 = {id: 1, name: “Tom”}
let obj2 = obj1;
obj1.name = “Mary” //obj2.name is also “Mary”

obj1 and obj2 point to the same memory address


Arithmetic operators

• Addition : + Subtraction: - Multiplication: * Division: / Remainder: %


• Exponentiation: **
• Increment/decrement
• Increment/Decrement a variable by one unit:
• a++ a-- ++a --a
• The operand must be an integer variable
• a++ and a– return the current value of a and then increment/decrement the value
of a,
• ++a and --a do the opposite , increment/decrement the value of a then return the
new value of a.

let counter = 1; let counter = 1;


alert( 2 * ++counter ); // 4 alert( 2 * counter++ ); // 2

7
Bit operators

• & (AND), | (OR), ^ (XOR), ~ (NOT), << (left shift), >> (right shift)
• A = 25 (11001)
B = 20 (10100)
• A&B • A&B ⇒ 16 (10000)
• A|B • A|B ⇒ 29 (11101)
•A^B • A ^ B ⇒ 13 (01101)
• ~A • ~A ⇒ 6 (00110)
• A<<2 • A<<2 ⇒ 100 (1100100)
• A>>2 • A>>2 ⇒ 6 (00110)

8
Comparisons

• > , < , >= , <=


• Equals: == Not equals: !=
• All comparison operators return a Boolean value
• Strings are compared letter-by-letter (Unicode order)
• Compare different types  converts to numbers alert( ‘4' > 1 ); // true
alert( '01' == 1 ); // true

• Strict equality operator ===: checks the equality without type conversion
alert( 0 == false ); // true
alert( 0 === false ); // false
• For null and undefined value:
• math operators, and < > <= >= operators
• null becomes 0, while undefined becomes NaN
• for == and ===
alert( null === undefined ); // false
alert( null == undefined ); // true, equal each other but not any other value

9
Logical operators

• AND (&&), OR (||), NOT (!)


• Logical expression is an expression containing logical operators, boolean values
• Returns 1 (true) or 0 (false)
• If an operand is not a Boolean, it’s converted to a Boolean for the evaluation
• multiple OR’ed values
• returns the first truth value or the last one if no truth value is found
alert( 1 || 0 ); // 1 (1 is truth)
alert( null || 1 ); // 1 (1 is the first truth value)
alert( null || 0 || 1 ); // 1 (the first truth value)
alert( undefined || null || 0 ); // 0 (all false, returns the last value)

• multiple AND’ed values


• returns the first false value or the last value if none were found

10
Other operators

• Numeric conversion
alert( +true ); // 1
alert( +"" ); // 0
• For String
let s = "my" + "string";
alert(s); // mystring

alert( '1' + 2 ); // "12"


alert( 2 + '1' ); // "21"

alert(2 + 2 + '1' ); // "41" and not "221“


alert('1' + 2 + 2); // "122" and not "14"

Other arithmetic operators work only with numbers and always convert their operands
to numbers.

11
Operator precedence

12
Operator precedence

• Indicates which operator comes first


• Is defined by the parentheses or by default as in Operator Precedence Table
(top-down priority is preceded):

https://developer.mozilla.org/
en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence 13
2. Expression

14
Expression

• An expression that contains at least one operand and 0 or more


operators
• The operands can be: constant values, literals, variables, result of a
function or subexpressions
• Operators have different precedence, but can be changed using
brackets ()
• Operators with the same precedence are performed from left to
right
• Examples:
• 47
• i
• x++
• sin(x+2)
• ( 2 * log( ( 3 + 10 ) - ( 2 * 6 ) ) )

15
Conditional Expressions

• Comparison operator

16
Conditional Expressions (2)

• Logical operators

17
Expressions vs. Statements

• An expression produces a value and can be written wherever a value is


expected
• as an argument in a function call
• at the right side of an assignment
• A statement performs an action
• A program is basically a sequence of statements
• Wherever JavaScript expects a statement, you can also write an expression
• Such a statement is called an expression statement.
• But, cannot write a statement where JavaScript expects an expression

18
Exercises

• Check the values of all variables after the code below?


let a = 1, b = 1; let a = 2;
let c = ++a; // ? let x = 1 + (a *= 2);
let d = b++; // ?

• Explain these expressions?


"" + 1 + 0 "4" - 2
"" - 1 + 0 "4px" - 2
true + false " -9 " + 5
6 / "3" " -9 " - 5
"2" * "3" null + 1
4 + 5 + "px" undefined + 1
"$" + 4 + 5 " \t \n" - 2

19
Chapter 5: Statements

1
Content

1. Statement, Block of statements


2. Declaration and Assignment statements
3. Conditional statement
4. Loop statement

2
1. Statement, Block of statements

• A statement performs an action


• Any statement can always be replaced by a block
• curly braces containing zero or more statements
• Normally, statements are terminated by semicolons
• The exception is statements ending with blocks
• No Semicolon After a Statement Ending with a Block
• An empty statement means does nothing
• ; or {}

3
2. Declaration and Assignment statements

• let is used to declare a variable: creates the variable and enables to work
with it
• Assignment operator (=) is used to assign a value to it

4
Control structure

• These are instruction structures that specify the program to execute different
commands / scripts, depending on certain conditions.
• Including control flow statements :
• Conditional statement
• if – else,
• switch – case
• Loop statement
• for
• while
• do – while

5
3. Conditional statement

6
if statement

• Syntax
if (condition){
statements;
}

• If the conditional expression (boolean type) gets true, then execute the command
block;

// add statements here // add statements here

if (year == 2022) {
alert( "That's 2022!" );
alert("Welcome to 2022!" );
}

7
if – else statement

 Syntax
if (condition){
‘true’ statements;
}
else {
‘false’ statements;
}
 If the conditional expression (boolean type) gets true, then execute the block
‘true’ statements , otherwise, execute the block ‘false’ statements.

if (year == 2022) {
alert('Welcome to 2022!' );
} else {
alert( 'Let \’s choose another year' );
}

8
else-if statement

• Syntax
if (condition_1){
statements;
}
else if (condition_2){
statements;
} else if (condition_3){
statements;
} else {
statements;
}

• Can have many else-if, but one else only if (time < 12) {
alert( 'Too early...' );
} else if (time > 12) {
alert( 'Too late' );
} else {
alert( 'Exactly!' );
}

9
Example - Check for an odd - even number

let num =10;


if (num %2 == 0)
alert (num+ “la so chan”);
else
alert (num + “la so le”);

10
Conditional operator ‘?’

• Condition ? TRUE_Part : FALSE_Part ;


• let A = (10<15) ? 100 : 200 ; //⇒ A = 100

let age = prompt('age?', 18);

let message = (age < 3) ? 'Hi, baby!' :


(age < 18) ? 'Hi boy!' :
(age < 100) ? 'Hello dad!' :
'What an unusual age!';

alert( message );

• rewrite the code with if..else ?

11
switch – case statement

• Check for a single variable for different values


and execute the corresponding commands
• A switch statement can replace multiple if checks
• The value is checked for a strict equality

12
switch – case statement(2)

• Syntax :
switch(expression) {
[true]
case x: case a
case a break
[false] action(s)
// code block
break; [true]
case y: case b
[false]
case b
action(s)
break

// code block
break;
.
default: .
.

// code block [true]

} case z
[false]
case z
action(s)
break

• break: exit the switch-case default


action(s)
• Cases cannot be repeated
• default controls values ​outside of case values
• If no case is matched then the default code is executed
• If there is no break then the execution continues with the next case without any
checks.

13
Example

switch (day) {
case 0:
case 1:
rule = “weekend”;
break;
case 2:
case 3:
case 4:
case 5:
case 6:
rule = “weekday”;
break;
default:
rule = “error”;
}

Replace switch-case statement with if-else statement?

14
4. Loop statement

15
While and do while loops

• Execute a statement or block while the


condition is still true

while (condition) {
// code block to be executed
}

do {
// code block to be executed
}
while (condition);

• while() executes 0 or more times


• do...while() executes at least once

16
Example

let i = 0; let i = 0;
while (i < 3) { // shows 0, then 1, then 2 do {
alert( i ); alert( i );
i++; i++;
} } while (i < 3);

let i = 3;
while (i) alert(i--);

let i = 0; let i = 0;
while (++i < 5) alert( i ); while (i++ < 5) alert( i );

Attention: Avoid endless loops!


(there is always a command to change the loop counter variable)

17
Example(2)

let a = 5,fact = 1;
while (a >= 1){
fact *=a;
a--;
}
alert(“The Factorial of 5 is “+fact);

Result: “The factorial of 5 is 120”

Replace by do-while ?

18
for loop

• Syntax : for (start_expr; test_expr; increment_expr){


// code to execute repeatedly
}
• example : for (let i = 0; i < 3; i++) {
alert(i);
}

• 3 expressions (1) (2) (3) can be absent (replaced with corresponding statements
in the block)
let i = 0;
let i = 0;
for (; i < 3;) {
for (; i < 3; i++) {
alert( i++ );
alert( i );
}
}
• You can declare variables in the for statement
• Usually used to declare a counter variable
• Usually declared in the start expression
• The scope of the variable is limited in the loop

19
Example

for (let i = 0; i < 5; i++) alert( i ); for (let i = 0; i < 5; ++i) alert( i );

let i=1, sum=0;


for (i=1;i<=10;i+=2)
sum+=i;
alert (“Sum of first five old numbers is “ + sum);

Result: “Sum of first five odd numbers is 25”

20
Use for and while

• The for and while statements provide equivalent functionality


• Loop statements are often used in different situations
• while is used for end-to-end iterations, with an unknown number of iterations.
• for is used to loop with a specified number of iterations.

let sum = 0; let sum = 0;


let index = 1; for (let index = 1;index <= 10;index++)
while (index <= 10) {
{ sum += index;
sum += index; }
index++;
}

21
Use for and while (2)

• Commands to change control flow:


• break
• used to early end a for, while or do...while
• There are two forms:
• Labeled: Resumes execution of the next statement after the labeled loop
• Untagged: Execute the next statement outside of the loop
• continue
• Used for a for, while or do...while to skip the remaining statements
of the current iteration and move on to the next iteration.
let sum = 0; for (let i = 0; i < 10; i++) {
while (true) { if (i % 2 == 0) continue;
let value = +prompt("Enter a number", ''); alert(i);
if (!value) break; // (*) }
sum += value;
}
alert( 'Sum: ' + sum );

22
Example

let sum = 0;
outer: for (let i=0; i<x; i++) {
inner: for (let j=i; j<x; j++){
sum++;
if (j==1) continue;
if (j==2) continue outer;
if (i==3) break;
if (j==4) break outer;
}
}

23
"for..in" loop

• to loop over object properties


for (key in object) {
// executes the body for each key among object properties
}

let user = { let codes = {
name: "Peter", "29": “coffee",
age: 26, "27": “tea",
isStudent: true "33": “water",
}; // ..,
"1": “check"
for (let key in user) { };
alert( key ); // name, age, isStudent
alert( user[key] ); // Peter, 26, true for (let code in codes) {
} alert(code); // 1, 27, 29, 33
}

24
for..of, forEach loop

• to loop over array elements

let arr = [“coffee", “tea", “water"]; let fruits = ["coffee", “tea", “water"];
for (let i = 0; i < arr.length; i++) { // iterates over array elements
alert( arr[i] ); for (let fruit of fruits) {
} alert( fruit );
}

25
Exercises

• Write an .html file, to ask user a question, receipt the answer. Check if their
answer is correct, appear a new window to notice them.
• Write a loop which prompts for a number greater than x. If the visitor enters
another number – ask them to input again. (x is entered by user)
• Write the code to print out all prime numbers in the interval from 2 to n. (n is
entered by user)

26
Chapter 6: Function

1
Content

• 1. Function Oriented Programming Concept


• Function concept
• Function calling
• 2. Function in JavaScript
• Function declaration
• Parameters specification
• Global and local variables
• Return specification
• 3. Advanced technique with functions

2
1. Function Oriented Programming concept

• Function-oriented programming method (or structured


programming) is a method that allows to divide a program function
(parent function) into smaller functions (called child functions).
• can be repeated for the sub-functions, until the functions are small
enough and need not to be divided any more (then they are called prime
functions).
• Example

Solve the quadratic equation

Enter the coefficients Calculate delta Calculate the solution

3
Function Oriented Programming concept

• Data connection between functions


parent function

Input data Output data

child function

Solve the quadratic equation


data
without
content

data with
content
Enter the coefficients Calculate delta Calculate the solution

4
Concept of function

• A function is a block of statements that perform a certain task, and


can be called as needed
• Using the function helps:
• Break down the program into many sub problems
• Reuse one or more times in one or more programs/projects
• Each function has to be defined before being used
• A name
• A number of parameters/arguments (can be empty)
• A returned value
• Corresponding block of statements

5
Function calling

• Calling a function:
• Through its name
• Send input data to the function through parameters
• Run the block of code with input data
• Return output data to the calling program through returned value or
parameters

B() return
call
A()

6
2. Function in JavaScript

• Definition of a function
• function <function-name> (<formal parameters definition>) {
Declare the variables used inside the function
Function statements
[return statement]
}
• Each function needs one and only one definition
• JavaScript is “type less” so no need to define return_type for returned value,
and parameters.

• Calling a function: <function-name> (<real parameters>)


• return statement: to exit the function and return a value to the calling program

7
Parameters specification

• Parameters/arguments
• in function definition: formal parameters (dummy names) represent
values/variables supplied to the function when it is called
• in function calls: the real parameters passed to this function call
• when a function is called, each formal parameter will be evaluated and
assigned to the coresponding value

function sum(m, n){ // m and n are two dummy names


// for two formal parameters of
// the function sum
}

c = sum(a, b); // a and b are real parameters passed


// to the call of function sum

d = sum(c, a);

8
Parameters specification

• Parameters/arguments
• when a function is called, each parameter will be evaluated and
assigned to the coresponding value.
• The parameters get value from the real value/variable supplied
(make a copy of value)

function showMessage(from, text) { parent function


alert(from + ': ' + text);
} Input data Output data

showMessage('Ann', 'Hello!'); child function


showMessage('Ann', "What's up?");

9
Pass By Value

• The function's parameter is a temporary variable, created on call and deleted on


exit of the function  local variable of the function
• Changing the value of the parameter does not affect the original variable

function assign10(x){
...
x = 10; x
} 20  10

let a = 20; copy


assign10(a); a
alert(a);
20

10
Pass by Reference

• Array and Object follows pass by reference


• make a copy of value, but the value now is address
function check(obj) {
let tmp = obj.a;
obj.a = obj.b;
obj.b = tmp;
console.log(`Inside a = ${obj.a} b = ${obj.b}`);
}
let obj = { Before a = 10 b = 20
a: 10, Inside a = 20 b = 10
b: 20 After a = 20 b = 10
}
console.log(`Before a = ${obj.a} b = ${obj.b}`);
check(obj)
console.log(`After a = ${obj.a} b = ${obj.b}`);

changing the value inside the function also change the original value

11
Pass by Reference

• Array and Object follows pass by reference


• make a copy of value, but the value now is address
function check(obj) {
obj = {
a: 40, b: 50, c: "CHECK"
}
console.log(`Inside a = ${obj.a} b = ${obj.b} c=${obj.c}`);

} Before a = 10 b = 20 c=undefined
let obj = { Inside a = 40 b = 50 c=CHECK
a: 10, After a = 10 b = 20 c=undefined
b: 20
}
console.log(`Before a = ${obj.a} b = ${obj.b} c=${obj.c}`);
check(obj)
console.log(`After a = ${obj.a} b = ${obj.b} c=${obj.c}`);

12
Default values

• In a function call, if an argument is not provided, then the corresponding


value becomes undefined  not good !
• The “default” value for a parameter
function showMessage(from, text = “empty text") {
alert( from + ": " + text );
}

showMessage(“Input"); // Input: empty text


showMessage(“Input", undefined); // Input: empty text

function showMessage(from, text = anotherFunction()) {


// anotherFunction() only executed if no text given
// its result becomes the value of text
}

• default parameter is evaluated only when the function is called without the
respective parameter.

13
Global and local variables

• Local variable:
• A variable declared inside a function
• only visible inside that function
• and destroyed after the end of the function

function showMessage() {
let message = "Hello, I'm JavaScript!";
alert( message );
}
showMessage(); // Hello, I'm JavaScript!
alert( message ); // <-- Error!

• Function parameters/arguments are local variables of that function


• automatically allocated when the function is called
• automatically deallocated when the function returns

14
Global and local variables

• Outer variables
• A function can access an outer variable
• and modify it

let userName = 'Peter';


function showMessage() {
userName = “Mary”;
let message = 'Hello, ' + userName; Peter
alert(message); Hello, Mary
} Mary
alert( userName );
showMessage();
alert( userName );

15
Global and local variables

• Outer variables
• If a same-named variable is declared inside the function then it shadows the
outer one.
let userName = 'Peter';
function showMessage() {
let userName = “Mary”; Peter
let message = 'Hello, ' + userName; Hello, Mary
alert(message); Peter
}
alert( userName );
showMessage();
alert( userName );

• Global variable: is declared outside of any functions


• has scope throughout the program, and exists during runtime
• accessed by all functions defined after (unless shadowed by locals)

16
Global and local variables

• Variable in loop statement:


• Has scope in one iteration of the loop
• Each iteration creates a new variable and initializes it again
• Example:
• let x = 20;
for (i=0; i<10; i++) {
let y = 20;
x++; y++;
alert(x + “,” + y);
}

17
Return specification

• Return a value back into the calling code as the result


function sum(a, b) {
return a + b; // or return (a+b);
}

let result = sum(1, 2);


alert( result ); // 3

• Many occurrences of return in a single function


function check (age) {
if (age >= 18) {
return true;
} else {
return confirm(‘Really want to access?’);
}
}

18
Return specification

• Return without a value


function showMovie(age) {
if ( !check(age) ) {
return;
}
alert( “Welcome !" );
}

• No return
• the same as if it returns undefined, or return empty
function doNothing1() { /* empty */ }

function doNothing2() {
return;
}

alert( doNothing()1 === undefined ); // true


alert( doNothing2() === undefined ); // true

19
3. Advanced technique with functions

20
Function is a value

• In JavaScript, a function is a value/variable


function sayHi() {
alert( "Hello" );
}
alert( sayHi );
// does not run the function, no parentheses after sayHi
// but shows the function code: string representation for this “variable”

• can work with it like with other kinds of values:


• pass it between variables and run when we want
// (1) create the function and puts it into the variable named sayHi
function sayHi() {
alert( "Hello" );
}

let func = sayHi; // (2) copy


func(); // (3) run the copy (it works)! - // Hello
sayHi(); // this still works too - // Hello

21
Function Expressions

• Create a new function in the middle of any expression


// (1) use a Function Expression to declare sayHi
let sayHi = function() {
alert( "Hello" );
};

• in an assignment expression
• a variable sayHi getting a value, the new anonymous function, created as function() {
alert("Hello"); }
• create a function and assign it into the variable sayHi
• Omitting a name is allowed (anonymous)

22
Function Expressions

• Use case of Function Expression


let age = prompt("What is your age?", 18); let age = prompt("What is your age?", 18);
if (age < 18) { let welcome;
function welcome() { if (age < 18) {
alert(“Please come back!"); welcome = function() {
} alert("Please come back!");
} else { };
function welcome() { } else {
alert(“Please go ahead!"); welcome = function() {
} alert("Please go ahead!");
} };
}
// ...use it later welcome(); // ok now
welcome(); // Error:
// welcome is not defined in the scope
let age = prompt("What is your age?", 18);
let welcome = (age < 18) ?
function() { alert("Please come back!"); } :
function() { alert("Please go ahead!"); };
welcome(); // ok now 23
Callback functions

• Function is a value so it can be passed in as the argument to another function

function ask(question, yes, no) {


if (confirm(question)) yes();
else no();
}

function showOk() {
alert( "You have booked a flight." );
}

function showCancel() {
alert( "You canceled a flight." );
}

// usage: functions showOk, showCancel are passed as arguments to ask


ask("Do you agree to book this ticket?", showOk, showCancel);

callback functions
24
Callback functions

• use Function Expressions example

function ask(question, yes, no) {


if (confirm(question)) yes()
else no();
}

ask(
"Do you agree to book this ticket?",
function() { alert("You have booked a flight."); },
function() { alert("You canceled a flight."); }
);

25
Arrow functions

Function Expressions Arrow functions (shorter version)


let func = function(arg1, arg2, ..., argN) {
return expression;
let func = (arg1, arg2, ..., argN) => expression;
};

• Creates a function func that accepts arguments arg1..argN, then evaluates


the expression on the right side and returns its result.
• Example:
let sum = function(a, b) {
return a + b; let sum = (a, b) => { a + b };
}; alert( sum(1, 2) ); // 3
• with 1 parameter
let double = function(n) { let double = n => n * 2;
return n * 2
}
• without parameter
let sayHi = () => alert("Hello!");

26
Arrow functions

• Arrow functions can be used in the same way as Function Expressions


let age = prompt("What is your age?", 18);

let welcome = (age < 18) ?


() => alert(‘Please come back!') :
() => alert(" Please go ahead!");

welcome();

• Multiline arrow functions


let sum = (a, b) => { // the curly brace opens a multiline function
let result = a + b;
return result; // need an explicit "return"
};

alert( sum(1, 2) ); // 3

27
Nested functions

• Nested functions:
• A function is called “nested” when it is created inside another function

function say(firstName, lastName) {


function getFullName() {
return firstName + " " + lastName;
}
alert( "Hello, " + getFullName() );
// do sth....
alert( "Bye, " + getFullName() );
}

28
forEach

• forEach: method of Javascript array


• calls a function for each element in an array

let sum = 0;
const numbers = [65, 44, 12, 4];
numbers.forEach(myFunction);

function myFunction(item) {
sum += item;
}

function myFunction(item, index, arr) {


arr[index] = item * 10;
}

29
Others...

• Rest parameters ...


• gathers the rest of the list of arguments into an array
• ... is at the end of function parameters
• create functions that accept any number of arguments
• The “arguments” variable
• a special array-like object named arguments that contains all arguments by their index
• Spread syntax
• opposite to rest parameters
• expands an array into a list
• ... occurs in a function call or alike
• pass an array to functions that normally require a list of many arguments

30
Exercises

• Write a function to output prime numbers up to n, with n is parameter of the


function.
• Write a function min(a,b)

31
Exercises

• Write a function sumTo(n) that calculates the sum of numbers 1 + 2 + ... + n


• Write a function fib(n) that returns the n-th Fibonacci number

32

You might also like