0% found this document useful (0 votes)
30 views

JavaScript Review Module Pattern, ES6+ Classes, Arrow Functions E.T.C

The document discusses web application development using full-stack JavaScript. It compares the MEAN and MERN stacks, which allow building web apps using MongoDB, Express, and Node.js, with either Angular or React for the front-end. It also explores advances in JavaScript, including modules, classes, and new keywords like let and const introduced in ECMAScript 6 and newer versions.

Uploaded by

c.34
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

JavaScript Review Module Pattern, ES6+ Classes, Arrow Functions E.T.C

The document discusses web application development using full-stack JavaScript. It compares the MEAN and MERN stacks, which allow building web apps using MongoDB, Express, and Node.js, with either Angular or React for the front-end. It also explores advances in JavaScript, including modules, classes, and new keywords like let and const introduced in ECMAScript 6 and newer versions.

Uploaded by

c.34
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 52

Web App Development

10/06/2023 Web App Development 1


Web Technology Stacks and Supporting
JavaScript Features
Objectives:
 Compare MEAN and MERN full stack architecture
 Explore the advancements in JavaScript.
 Use Module pattern
 Examine Event-Driven Model
 Apply ES6+ Features

10/06/2023 Web App Development 2


Full-Stack JavaScript
 In 2008, Google released its Chrome browser, along
with its fast JIT-compiling V8 JavaScript engine.
 Google's V8 engine made JavaScript run so much faster that it
completely transformed web application development.
 One of the first products of this revolution was Node.js.
 a V8-based database called MongoDB.
 A frontend open source framework called AngularJS.
 A frontend library called React.
 Now JavaScript is the programming language across
all three layers - an idea that is commonly referred to
as the full-stack JavaScript.
 The following stacks are examples of this idea:
 The MEAN (MongoDB, Express, Angular, Node) stack
 The MERN (MongoDB, Express, React, Node) stack

10/06/2023 Web App Development 3


Programming, Scripting, Markup

10/06/2023 Web App Development 4


https://insights.stackoverflow.com/survey/2021#most-popular-technologies-language-prof
Web Frameworks/Libraries

10/06/2023 Web App Development 5


Front-End Frameworks/Libraries

10/06/2023 Web App Development 6


https://www.npmtrends.com/angular-vs-react-vs-vue
Jamstack Community Survey 2022

10/06/2023 Web App Development 7


https://jamstack.org/survey/2022/#choices
Jamstack Community Survey 2022

10/06/2023 Web App Development 8


https://jamstack.org/survey/2022/#choices
The State of Developer Ecosystem
2022

10/06/2023 Web App Development 9


https://www.jetbrains.com/lp/devecosystem-2022/
Web Technology Stacks
 LAMP stack:
 Linux
 Apache
 MySQL
 PHP/Python/Perl
 .NET (Core) stack:
 .NET (Core)
 IIS
 ASP.NET (Core)
 Web API and WCF
 MS-SQL Server
 Other frameworks and tools (Django, Flask, etc.)
 Each layer uses a different knowledge base!

10/06/2023 Web App Development 10


MEAN Stack
 MEAN is an abbreviation for MongoDB, Express, AngularJS, and
Node.js.
 Uses only JavaScript - driven solutions to implement the
different parts of a web application.
 Has the following advantages:
 A single language is used throughout the application
 All the parts of the application can support and often enforce
the use of the MVC architecture
 Serialization and deserialization of data structures is no longer
needed because data marshaling is done using JSON
objects.

10/06/2023 Web App Development 11


MEAN Stack
 MongoDB is a scalable NoSQL database that used a
JSON-like data model with dynamic schemas.
 Express is a lightweight node.js web application
framework, providing a robust set of features for
building single and multi-page, and hybrid web
application.
 Node.js is a server side JavaScript execution
environment built on Google Chrome’s V8 JavaScript
runtime - helps in building highly scalable and
concurrent applications rapidly.
 Angular is a JavaScript framework developed by
Google - a complete solution for rapid front end
development.

10/06/2023 Web App Development 12


LAMP versus MEAN
 Linux  Node.js (platform)

 Apache  Express.js (web server framework)

 MySQL  MongoDB (persistence layer)

 PHP or Python or Perl  Angular (User Interface)

10/06/2023 Web App Development 13


MERN Stack
 MongoDB
 Express
 Node.js
 ReactJS is a JavaScript component-based front-end
library maintained by Facebook – most popular for
front-end development.

10/06/2023 Web App Development 14


MEAN and MERN Advantages
 High Performance
 Increasing number of requests
 Reducing response time
 Non-blocking I/O - allows web server to handle more
concurrent requests without requiring additional
hardware or configuration
 Cross-platform (Windows, Linux, MacOS)
 One single programming language for the entire
project

10/06/2023 Web App Development 15


The Evolution of JavaScript
 The standard for JavaScript is ECMAScript.
 On June 17, 2015, ECMA International published the
sixth major version of ECMAScript, which is officially
called ECMAScript 2015, and is more commonly
referred to as ECMAScript 6 or ES6.
 Since then ECMAScript standards are on yearly release
cycles.
 Here is the ES6 guide:
 https://leanpub.com/ecmascript2015es6guide/read
 Current versions of Chrome, Firefox, Edge, Safari, and
Opera support ES6 features.
 ECMAScript 2021
(https://262.ecma-international.org/12.0/) is the current
version.
10/06/2023 Web App Development 16
https://developer.mozilla.org/en-US/docs/Web/JavaScript
ES6 - Modules
 Modules
 export – to expose the module
 import – to make the module available to use
 Example: suppose you have a file named lib.js that
contains the following code:
export function halfOf(x) {
return x / 2;
}
 In your main.js file, you can use the following code:
import halfOf from 'lib';
console.log(halfOf(84));

10/06/2023 Web App Development 17


ES6 - Modules
 Exporting multiple functions:
 If lib.js file looks like this:
export function halfOf(x) {
return x / 2;
}
export function multiply(x, y) {
return x * y;
}
 In your main.js file, use the following code:
import {halfOf, multiply} from 'lib';
console.log(halfOf(84));
console.log(multiply(21, 2));

10/06/2023 Web App Development 18


ES6 - Modules
 Named export are used to export multiple things from a
module by adding the keyword export to their declaration.
 There can be multiple named exports in a module and they
are imported using the name that were used to export.
 Default export allows only a single default export per module
and we can assign it any name when importing it from another
module or file.
 Example: doSomething.js that contains the following code:
export default function () {
console.log('I did something')
};
 You'll be able to use it as follows in your main.js file:
import doSomething from 'doSomething';
doSomething();
 However, is not possible to use var, let or const with export
default
10/06/2023 Web App Development 19
ES6 - Modules
 Modules export bindings - live connections to values,
not just values.
 Example: a validator.js file that looks like this:
export let flag = false;
export function touch() {
flag = true;
}
 You also have a main.js file that looks like this:
import { flag, touch } from 'validator';
console.log(flag);
touch();
console.log(flag);
 The first output would be false, and the second would
be true because is modified in function touch.

10/06/2023 Web App Development 20


Let and Const
 Let and Const are new keywords used for symbol
declaration.
 Let statement declares a block scope local variable.
 Here is an example:
function iterateVar() {
for(var i = 0; i < 10; i++) {
console.log(i);
}
console.log(i) //will print i
}
function iterateLet() {
for(let i = 0; i < 10; i++) {
console.log(i);
}
console.log(i) //will throw an error
}

10/06/2023 Web App Development 21


Let and Const
 The first function will print i after the loop, but the
second one will throw an error, since i is defined by let,
therefore not defined outside the block.

 The const keyword forces single assignment.


 So, this code will throw an error as well:
const me = 1
me = 2 //cannot reinitialize

10/06/2023 Web App Development 22


Trying Out ES6
 Use jsfiddle (https://jsfiddle.net/) or Babeljs:

10/06/2023 Web App Development 23


ES6 - Classes
 Classes in ES6 are basically just a syntactic sugar over
the prototype-based inheritance.
class Vehicle {
constructor(wheels) {
this.wheels = wheels;
}
toString() {
return '(' + this.wheels + ')';
}
}
class Car extends Vehicle {
constructor(color) {
super(4);
this.color = color;
}
toString() {
return super.toString() + ' colored: ' + this.color;
}
}

10/06/2023 Web App Development 24


ES6 - Classes
let car = new Car('blue');
car.toString();
console.log(car instanceof Car);
console.log(car instanceof Vehicle);

 In this example, the Car class extends the Vehicle


class.
 The output is as follows:
(4) in blue
true
true

10/06/2023 Web App Development 25


Class Example on Babel
a

10/06/2023 Web App Development 26


Class Example in Browser
<div id="output"></div>
<!-- Load Babel -->
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<!-- Your custom script here -->
<script type="text/babel" data-presets="es2016,es2017,stage-2, stage-3">
class Vehicle {
constructor(wheels) {
this.wheels = wheels;
}
toString() {
return '(' + this.wheels + ')';
}
}
class Car extends Vehicle {
constructor(color) {
super(4);
this.color = color;
}
toString() {
return super.toString() + ' colored: ' + this.color;
}
}
let car = new Car('blue');
document.getElementById('output').innerHTML = car.toString() + "<br>";;
document.getElementById('output').innerHTML += (car instanceof Car) + "<br>";
document.getElementById('output').innerHTML += (car instanceof Vehicle);

</script>

10/06/2023 Web App Development 27


Class Example on https://jsfiddle.net/
<div id="output"></div>
<script >
class Vehicle {
constructor(wheels) {
this.wheels = wheels;
}
toString() {
return '(' + this.wheels + ')';
}
}
class Car extends Vehicle {
constructor(color) {
super(4);
this.color = color;
}
toString() {
return super.toString() + ' colored: ' + this.color;
}
}
let car = new Car('red');
document.getElementById('output').innerHTML = car.toString() + "<br>";;
document.getElementById('output').innerHTML += (car instanceof Car) + "<br>";
document.getElementById('output').innerHTML += (car instanceof Vehicle);
</script>

10/06/2023 Web App Development 28


Class Example on https://jsfiddle.net/

10/06/2023 Web App Development 29


Arrow functions
 Arrows are functions shorthand by the => syntax.
 Used in Java and C#.
 Arrows are also very helpful because they share the same lexical
this as their scope.
 They are mainly used in two forms:
 using an expression body:
let numbers = [1,2,3,4,5]
const squares = numbers.map(n => n * n);
console.log('squares:',squares)
 using a statement body:
let evens = []
numbers.forEach(n => { //anonymous function code
if (n % 2 === 0) evens.push(n);
});
console.log('even numbers', evens)
10/06/2023 Web App Development 30
Arrow Functions and scope
 Lexical scoping means whatever variables are
in scope where you define a function from (as opposed
to when you call it) are in scope in the function
 An example of using the shared lexical would be:
const author = {
fullName: "Bob Alice",
books: [],
printBooks() {
this.books.forEach(book => console.log(book + ' by ' + this.fullName));
}
};
author.books = ["JavaScript", "Python", "Kotlin"]
author.printBooks()
 If used as a regular function, this would be the book
object and not the author.
10/06/2023 Web App Development 31
Default, Rest, and Spread
 Default, Rest, and Spread are three new features
related to functions parameters.
 The default feature allows you to set a default value to
the function parameter:
function add(x, y = 0) {
return x + y;
}
add(1)
add(1,2)
 In this example, the value of y will be set to 0 if a value
is not passed or is set to undefined.

10/06/2023 Web App Development 32


Rest Operator
 The Rest feature allows allows a function to accept
an indefinite number of arguments as an array:

function userFriends(user, ...friends) {


console.log(user + ' has ' + friends.length + ' friends');
}
userFriends('User', 'Bob', 'Alice');
 This will output:
User has 2 friends
 Only the last parameter in a function definition can be
a rest parameter.

10/06/2023 Web App Development 33


Spread Operator
 The spread operator is three dots (...) that perform
several different tasks.
 The spread operator turns an array into a call
argument:
function userTopFriends(firstFriend, secondFriend, thirdFriend) {
console.log(firstFriend);
console.log(secondFriend);
console.log(thirdFriend);
}
userTopFriends(...['Alice', 'Bob', 'Michelle']);
 This will output:
Alice
Bob
Michelle

10/06/2023 Web App Development 34


Spread Operator
 We can also use the three dot syntax to collect function
arguments as an array.
 When used in a function, these are called rest parameters.
 Here, we build a function that takes in n number of arguments
using the spread operator, and then uses those arguments to print
some console messages:
function directions(...args) {
let [start, ...remaining] = args;
let [finish, ...stops] = remaining.reverse();
//
console.log(`drive through ${args.length} towns`);
console.log(`start in ${start}`);
console.log(`the destination is ${finish}`);
console.log(`stopping ${stops.length} times in between`);
}
directions("Truckee", "Tahoe City", "Sunnyside", "Homewood",
"Tahoma");

10/06/2023 Web App Development 35


Learning React, 2nd Edition, O’Reilly
Spread Operator
 The directions function takes in the arguments using
the spread operator.
 The first argument is assigned to the start variable.
 The last argument is assigned to a finish variable using
Array.reverse.
 We then use the length of the arguments array to
display how many towns we’re going through.
 The number of stops is the length of the arguments
array minus the finish stop.
 This provides incredible flexibility because we could use
the directions function to handle any number of stops.

10/06/2023 Web App Development 36


Learning React, 2nd Edition, O’Reilly
Spread Operator
 Allows us to combine the contents of arrays.
 For example, if we had two arrays, we could make a third
array that combines the two arrays into one:
const peaks = ["Tallac", "Ralston", "Rose"];
const canyons = ["Ward", "Blackwood"];
const tahoe = [...peaks, ...canyons];
console.log(tahoe.join(", ")); // Tallac, Ralston, Rose,
Ward, Blackwood
 All of the items from peaks and canyons are pushed into a new
array called tahoe.
 The spread operator can also be used to get the remaining items
in the array:
const lakes = ["Donner", "Marlette", "Fallen Leaf",
"Cascade"];
const [first, ...others] = lakes;
console.log(others.join(", ")); // Marlette, Fallen Leaf,
Cascade
10/06/2023 Web App Development 37
Learning React, 2nd Edition, O’Reilly
Spread Operator
 The spread operator can also be used for objects.
 In this example, we’ll use it the same way we combined two arrays
into a third array, but instead of arrays, we’ll use objects:
const morning = {
breakfast: "oatmeal",
lunch: "peanut butter and jelly"
};
const dinner = "mac and cheese";
const backpackingMeals = {
...morning,
dinner
};
console.log(backpackingMeals);
// {
// breakfast: "oatmeal",
// lunch: "peanut butter and jelly",
// dinner: "mac and cheese"
// }

10/06/2023 Web App Development 38


Learning React, 2nd Edition, O’Reilly
Function Expressions
 Another option is to use a function expression.
 This just involves creating the function as a variable:
const logCompliment = function() {
console.log("You're doing great!");
};
logCompliment();
 Note that:
 you can invoke a function before you write a function
declaration.
 you can not invoke a function created by a
function expression before declaring it.

10/06/2023 Web App Development 39


Learning React, 2nd Edition, O’Reilly
Returning Objects
 Consider a function called person that builds an object
based on parameters passed in for firstName and
lastName.
 Wrap the object you’re returning with parentheses:
const person = (firstName, lastName) => ({
first: firstName,
last: lastName
});
console.log(person("Flad", "Hanson"));

10/06/2023 Web App Development 40


Learning React, 2nd Edition, O’Reilly
Destructuring Objects
 Destructuring assignment allows you to locally scope fields
within an object and to declare which values will be used.
 Consider the sandwich object:
const sandwich = {
bread: "dutch crunch",
meat: "tuna",
cheese: "swiss",
toppings: ["lettuce", "tomato", "mustard"]
};
 It has four keys, but we only want to use the values of two.
 We can scope bread and meat to be used locally:
const { bread, meat } = sandwich;
console.log(bread, meat); // dutch crunch tuna

10/06/2023 Web App Development 41


Learning React, 2nd Edition, O’Reilly
Destructuring Function Arguments
const lordify = ({ firstname }) => {
console.log(`${firstname} of Canterbury`);
};
const regularPerson = {
firstname: "Bill",
lastname: "Wilson"
};
lordify(regularPerson); // Bill of Canterbury

10/06/2023 Web App Development 42


Learning React, 2nd Edition, O’Reilly
Destructuring Arrays
 Assign the first value of an array to a variable name:
const [firstAnimal] = ["Horse", "Mouse", "Cat"];
console.log(firstAnimal); // Horse
 We can also pass over unnecessary values with list
matching using commas:
const [, , thirdAnimal] = ["Horse", "Mouse", "Cat"];
console.log(thirdAnimal); // Cat

10/06/2023 Web App Development 43


Learning React, 2nd Edition, O’Reilly
Object Literal Enhancement
 It’s the opposite of destructuring
 We can grab variables from the global scope and add
them to an object:
const name = "Tallac";
const elevation = 9738;
const funHike = { name, elevation };
console.log(funHike); // {name: "Tallac", elevation: 9738}
 name and elevation are now keys of the funHike object.

10/06/2023 Web App Development 44


Learning React, 2nd Edition, O’Reilly
Object Literal Enhancement
 We can also create object methods with object literal
enhancement:
const skier = {
name,
sound,
powderYell() {
let yell = this.sound.toUpperCase();
console.log(`${yell} ${yell} ${yell}!!!`);
},
speed(mph) {
this.speed = mph;
console.log("speed:", mph);
}
};
 Object literal enhancement allows us to pull global variables into
objects and reduces typing by making the function keyword
unnecessary.
10/06/2023 Web App Development 45
Learning React, 2nd Edition, O’Reilly
Asynchronous JavaScript
 JavaScript functions are executed in the sequence they
are called, not in the sequence they are defined.
 To handle asynchronous calls JavaScript uses:
 Callbacks
 Promises
 async/await statements

 A callback is a function passed as an argument to


another function.

 See the example in the next slide.

10/06/2023 Web App Development 46


Asynchronous JavaScript - Callbacks
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Callback</h2>

<p>Wait 3 seconds (3000 milliseconds) for this page to change.</p>

<h1 id="demo"></h1>

<script>
setTimeout(myFunction, 3000);

function myFunction() {
document.getElementById("demo").innerHTML = "callback executed !!";
}
</script>

</body>
</html>

10/06/2023 Web App Development 47


https://www.w3schools.com/js/js_callback.asp
Asynchronous JavaScript - Promises
 Promises are used to handle asynchronous operations in
JavaScript.
 A promise can be created using Promise constructor. syntax:
var promise = new Promise(function(resolve, reject){
//do something
});
var promise = new promise.
Promise(function(resolve, reject) { then(function () {
const x = "geeksforgeeks"; console.log('Success, You are a
const y = "geeksforgeeks" GEEK');
if(x === y) { }).
resolve(); catch(function () {
} else { console.log('Some error has
reject(); occured');
} });
});
10/06/2023 Web App Development 48
https://www.geeksforgeeks.org/javascript-promises/
Asynchronous JavaScript - Promises
 The promise is an object that represents whether the async
operation is pending, has been completed, or has failed.
 The then method will invoke the callback function once the
promise has resolved.
 Here is an example using fetch method to fetch resources
asynchronously across the network.
 A basic fetch call takes a url and returns a promise containing the
response:
fetch("https://api.randomuser.me/?nat=US&results=1").then(res =>
console.log(res.json()));
 Whatever you return from this function becomes the argument of
the next then function.
fetch("https://api.randomuser.me/?nat=US&results=1")
.then(res => res.json())
.then(json => json.results)
.then(console.log)
.catch(console.error);
10/06/2023 Web App Development 49
Learning React, 2nd Edition, O’Reilly
Async/Await
 The async and await keywords enable asynchronous, promise-
based behavior to be written in a cleaner style, avoiding the need
to explicitly configure promise chains.
const getFakePerson = async () => {
try {
let res = await fetch("https://api.randomuser.me/?
nat=US&results=1");
let { results } = res.json();
console.log(results);
} catch (error) {
console.error(error);
}
};
getFakePerson();

10/06/2023 Web App Development 50


Learning React, 2nd Edition, O’Reilly
Async/Await
 async makes a function return a Promise
 await makes a function wait for a Promise
 async keyword is placed in front of a function
declaration to turn it into an async function.

const getFakePerson = async () => { }


 Then await keyword is used inside the function:

let res = await fetch("https://api.randomuser.me/?nat=US&results=1");

 Multiple await statements are allowed.


 Use try/catch for exception handling.

10/06/2023 Web App Development 51


References
 Reference Textbooks
 https://leanpub.com/ecmascript2015es6guide/read
 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export
 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import
 http://www.2ality.com/2015/08/getting-started-es6.html
 https://leanpub.com/setting-up-es6/read
 http://exploringjs.com/es2016-es2017/index.html
 http://es6-features.org/
 https://tsh.io/state-of-microservices/?utm_source=event&utm_medium=social&utm_campaign
=soms_report&utm_content=webinar_backend#ebook
 https://techbeacon.com/app-dev-testing/top-5-software-architecture-patterns-how-make-right-c
hoice
 https://martinfowler.com/articles/micro-frontends.html#InANutshell
 Learning React, 2nd Edition, O’Reilly
 State-of-Frontend-2022-by-TSH
 https://www.htmlgoodies.com/beyond/javascript/the-model-view-viewmodel-pattern-and
-angular-development.html
 https://www.angularminds.com/blog/article/mvc-vs-mvp-mvvm.html
 https://jamstack.org/survey/2021/#choices
 https://www.jetbrains.com/lp/devecosystem-2022/

10/06/2023 Web App Development 52

You might also like