IS231: Web Technology
JavaScript-4 & AJAX
By: Neamat El Tazi
References
- W3shools.com
- https://www.geeksforgeeks.org/mvc-design-pattern/
- https://selftaughtcoders.com/from-idea-to-launch/lesson-17/laravel-5-
mvc-application-in-10-minutes/
2 Web Technology Neamat El Tazi
ECMAScript 2015 – ES6
ECMAScript 6, also known as ES6 and
ECMAScript 2015, was the second major
revision to JavaScript.
3 Web Technology Neamat El Tazi
New Features in ES6
The let keyword
The const keyword
JavaScript Arrow Functions
JavaScript Class
JavaScript Promise
Default Parameter Values
New Types Properties (check it on www.w3schools.com)
ES7,8,9,10,11,12
4 Web Technology Neamat El Tazi
The Var Keyword
Before ES6, the var keyword was used to declare a
variable in JavaScript. The var keyword has been around
since the inception of JavaScript, and it’s what you will
see in any pre ES6 code.
Variables declared using the var keyword are either
globally or functionally scoped, they do not support
block-level scope. This means that if a variable is defined
in a loop or in an if statement it can be accessed outside
the block and accidentally redefined leading to a buggy
program.
5 Web Technology Neamat El Tazi
The Var Keyword
6 Web Technology Neamat El Tazi
(ES6) Let Keyword
The let keyword is very similar to the var keyword as they
both allow you to reassign the value later. The main
difference between the two is that let deals with a block
scope and although it can be reassigned it cannot be
redeclared.
Generally, you should avoid using the var keyword and
use Let instead.
7 Web Technology Neamat El Tazi
Let Keyword
8 Web Technology Neamat El Tazi
JavaScript let keyword
The let keyword allows you to declare a variable with
block scope.
var x = 10;
// Here x is 10
{
let x = 2;
// Here x is 2
}
// Here x is 10
9 Web Technology Neamat El Tazi
JavaScript const
The const keyword allows you to declare a constant (a
JavaScript variable with a constant value).
Constants are similar to let variables, except that the value
cannot be changed.
var x = 10;
// Here x is 10
{
const x = 2;
// Here x is 2
}
// Here x is 10
10 Web Technology Neamat El Tazi
Arrow Functions
Arrow functions allows a short syntax for writing function
expressions.
You don't need the function keyword, the return keyword, and
the curly brackets.
// ES5
var x = function(x, y) {
return x * y;
}
// ES6
const x = (x, y) => x * y;
11 Web Technology Neamat El Tazi
Arrow Functions
Arrow functions do not have their own this. They are not well suited
for defining object methods.
They must be defined before they are used.
Using const is safer than using var, because a function
expression is always a constant value.
You can only omit the return keyword and the curly
brackets if the function is a single statement.
const x = (x, y) => { return x * y };
=
const x = (x, y) => x * y;
12 Web Technology Neamat El Tazi
Remember
//ES5
var numbers = [45, 4, 9, 16, 25];
var over18 = numbers.filter(myFunction);
function myFunction(value) {
return value > 18;
}
//ES6
var numbers = [45, 4, 9, 16, 25];
var over18 = numbers.filter((value)=>value>18);
Check Demo 20
13 Web Technology Neamat El Tazi
JavaScript Classes
JavaScript Classes are templates for JavaScript Objects.
Use the keyword class to create a class.
Always add a method named constructor():
Syntax
class ClassName {
constructor() { ... }
}
14 Web Technology Neamat El Tazi
JavaScript Classes
Classes were introduced in ES6 to provide a cleaner way
to follow object-oriented programming patterns.
JavaScript still follows a prototype-based inheritance
model. Classes in JavaScript are syntactic sugar over the
prototype-based inheritance model which we use to
implement OOP concepts.
Thus, the introduction of classes in JS made it easier for
developers to build software around OOP concepts. It
also brought in similarities to different OOP-based
programming languages such as C++ and Java.
15 Web Technology Neamat El Tazi
Before Classes
Before classes, we used constructor functions to do
OOP in JavaScript.
function Pen(name, color, price)
{
this.name = name;
this.color = color;
this.price = price;
}
const pen1 = new Pen("Marker", "Blue", "$3");
console.log(pen1);
https://www.freecodecamp.org/news/javascript-classes-how-they-work-with-use-case/
16 Web Technology Neamat El Tazi
Before Classes – Adding a function to a
constructor
function Pen(name, color, price) {
this.name = name;
this.color = color;
this.price = price;
}
const pen1 = new Pen("Marker", "Blue", "$3");
Pen.prototype.showPrice = function(){
console.log(`Price of ${this.name} is ${this.price}`);
}
pen1.showPrice();
17 Web Technology Neamat El Tazi
Using Class Keyword
class Pen {
constructor(name, color, price){
this.name = name;
this.color = color;
this.price = price;
}
showPrice(){
console.log(`Price of ${this.name} is ${this.price}`);
}
}
const pen1 = new Pen("Marker", "Blue", "$3");
pen1.showPrice();
18 Web Technology Neamat El Tazi
JavaScript Classes – Another example
Example
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
}
Using a Class
let myCar1 = new Car("Ford", 2014);
let myCar2 = new Car("Audi", 2019);
19 Web Technology Neamat El Tazi
Inheritance in Javascript Classes
class OfficeSupplies {
constructor(name, color, price){
this.name = name; this.color = color; this.price = price;
}
showPrice(){ console.log(`Price of ${this.name} is ${this.price}`);
}
}
class Pen extends OfficeSupplies {
constructor(type){
super();
this.type = type;
}
showType(){
console.log(`Type of ${this.name} is ${this.type}`); }}
20 Web Technology Neamat El Tazi
JavaScript Promise Object
A Promise is a JavaScript object that links "Producing Code" and
"Consuming Code".
"Producing Code" can take some time and "Consuming Code" must
wait for the result.
Promise Syntax
let myPromise = new Promise(function(myResolve, myReject) {
// "Producing Code" (May take some time)
myResolve(); // when successful
myReject(); // when error
});
// "Consuming Code" (Must wait for a fulfilled Promise).
myPromise.then(
function(value) { /* code if successful */ },
function(error) { /* code if some error */ }
);
21 Web Technology Neamat El Tazi
Example Using a Promise
let myPromise
= new Promise(function(myResolve, myReject)
{
setTimeout(function() { myResolve("I love
You !!"); }, 3000);
});
myPromise.then(function(value) {
document.getElementById("demo").innerHTML
= value;
});
22 Web Technology Neamat El Tazi
Default Parameter Values
ES6 allows function parameters to have
default values.
function myFunction(x, y = 10) {
// y is 10 if not passed or undefined
return x + y;
}
myFunction(5); // will return 15
23 Web Technology Neamat El Tazi
Function Rest Parameter
The rest parameter (...) allows a function to treat
an indefinite number of arguments as an array:
function sum(...args) {
let sum = 0;
for (let arg of args) sum += arg;
return sum;
}
let x = sum(4, 9, 16, 25, 29, 100, 66, 77);
Check Demo 22
24 Web Technology Neamat El Tazi
Array.find()
The find() method returns the value of the first array
element that passes a test function.
This example finds (returns the value of ) the first
element that is larger than 18:
var numbers = [4, 9, 16, 25, 29];
var first = numbers.find(myFunction);
function myFunction(value) {
return value > 18;
}
25 Web Technology Neamat El Tazi
New Global Methods: The isNaN() Method
The global isNaN() method returns true if the argument
is NaN. Otherwise it returns false
isNaN("Hello"); // returns true
//Try it
26 Web Technology Neamat El Tazi
New Global Methods: The isFinite() Method
The global isFinite() method returns false if the argument
is Infinity or NaN.
Otherwise it returns true:
isFinite(10/0); // returns false
isFinite(10/1); // returns true
isFinite(“hello”); // returns false
27 Web Technology Neamat El Tazi
AJAX
28 Web Technology Neamat El Tazi
ECMA2016 – ES7
Introduced only two new features:
Array.prototype.includes()
Exponential Operatator
29 Web Technology Neamat El Tazi
ES7 – Includes() feature
In ES6, we used to use indexOf() function to check if a
value exists in an array like the following:
Let numbers = [1,2,3,4]
if(numbers.indexOf(2) !== -1) { //do something}
In ES7, we can write:
Let numbers = [1,2,3,4]
if(numbers.includes(2)) { //do something}
30 Web Technology Neamat El Tazi
Difference between indexOf and includes
Array.prototype.includes() handles NaN better than
Array.prototype.indexOf(). If the array contains NaN,
indexOf() cannot handle it.
Array.prototype.includes() returns the correct value
when searching for NaN.
console.log(numbers.indexOf(NaN)); //Prints -1
console.log(numbers.includes(NaN)); //Prints true
31 Web Technology Neamat El Tazi
ES7 – Exponentiation Operator
CMAScript 2016 introduced the exponentiation operator,
**.
It has the same purpose as Math.pow(). It returns the first
argument raised to the power of the second argument.
let base = 3;
let exponent = 4;
let result = base**exponent;
console.log(result); //81
32 Web Technology Neamat El Tazi
ES8
ES8 introduces two string handling functions for
padding a string:
String.padStart()
String.padEnd()
Async and Await
33 Web Technology Neamat El Tazi
ES8 – padStart()
string_value.padStart(targetLength [, padString])
34 Web Technology Neamat El Tazi
ES8 – padEnd()
string_value.padEnd(targetLength [, padString])
35 Web Technology Neamat El Tazi
ES8 – Async and Await
Async/Await is a very important feature in ES8.
The await keyword is used with promises. This keyword
can be used to pause the execution of a function till a
promise is settled.
The await keyword returns value of the promise if the
promise is resolved while it throws an error if the
promise is rejected.
The await function can only be used inside functions
marked as async. A function that is declared using the
async keyword always returns a promise.
36 Web Technology Neamat El Tazi
ES8 – Async and Await --- in ES6
37 Web Technology Neamat El Tazi
ES8 – Async and Await
38 Web Technology Neamat El Tazi
Promise chaining with Async/await in ES8
39 Web Technology Neamat El Tazi
ES9
ES9 introduced:
Rest/Spread Properties
Promise: finally()
40 Web Technology Neamat El Tazi
ES9 - Rest/Spread Properties
The value of age property of
student is copied into the age
variable while the values of
the remaining properties are
copied into the other variable
using the rest syntax `...`
41 Web Technology Neamat El Tazi
ES9 – Promise Finally
The finally() is executed whenever a promise is settled, regardless of its
outcome. This function returns a promise. It can be used to avoid code
duplication in both the promise's then() and catch() handlers.
42 Web Technology Neamat El Tazi
ES9 – promise finally() Example
The following example declares a
async function that returns the
square of a positive number after a
delay of 3 seconds. The function
throws an error if a negative
number is passed. The statements
in the finally block is executed in
either case, whether the promise is
rejected or resolved.
43 Web Technology Neamat El Tazi
ES10 – ECMAScript2019
ES10 introduced some new functions/features:
flat() is a method which is used to flatten an array. There
are certain situations in which the elements of an array are
an array. These types of arrays are called nested arrays.
Normally to un-nest (flatten) them, we had to use
recursion. Now with the introduction of flat(), it can be
done in a single line. F.Y.I — a flattened array is an array
of depth 0
44 Web Technology Neamat El Tazi
ES10 – ECMAScript2019
ES10 introduced some new functions/features:
flatMap() is used to flatten a nested array and to change
the values according to a function like a map() function.
45 Web Technology Neamat El Tazi
ES11 – ECMAScript2020
ES11 introduced private class variables:
class HelloWorld {
#message = "How are you?"; //this is a private variable
getMessage()
{
console.log(this.#message)
}
}
const hello = new HelloWorld()
hello.getMessage() // How are you?
46 Web Technology Neamat El Tazi
ES12 and ES13
Small but useful features have been added to ES12, ES13
and now also in 2023 ES14
You can check them online.
47 Web Technology Neamat El Tazi
AJAX
AJAX is not a programming language.
AJAX is a technique for accessing web servers
from a web page.
AJAX stands for Asynchronous JavaScript And
XML.
48 Web Technology Neamat El Tazi
AJAX Example
HTML Page
<!DOCTYPE html>
<html>
<body>
<div id="demo">
<h2>Let AJAX change this text</h2>
<button type="button" onclick="loadDoc()
">Change Content</button>
</div>
</body>
</html>
49 Web Technology Neamat El Tazi
AJAX Example
Function loadDoc()
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status ==
200) {
document.getElementById("demo").innerHTML
= this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
50 Web Technology Neamat El Tazi
What is AJAX?
51 Web Technology Neamat El Tazi
AJAX Cycle
1. An event occurs in a web page (the page is loaded, a
button is clicked)
2. An XMLHttpRequest object is created by JavaScript
3. The XMLHttpRequest object sends a request to a web
server
4. The server processes the request
5. The server sends a response back to the web page
6. The response is read by JavaScript
7. Proper action (like page update) is performed by
JavaScript
52 Web Technology Neamat El Tazi
Next
MVC
Python (Back-end Programming Language)
Django (Web Applications Framework)
53 Web Technology Neamat El Tazi