made with ❤ by Pava
Hi! i am and
{ Pava }
😎 About you?
"Being a JavaScript developer is for me the 💖 {best} job in the world!
It feeds my 💡 {creativity}, keeps me 🥊 {challenged} and allows me to build what I want for whatever platform I need!" - Pava
📄 But before we begin...
⭐ ask when I don't explain clearly
⭐ REALLY ASK!
⭐ REALLY REALLY STOP ME AND ASK! OK?
🏠 there will be home assignments between sessions
Can we have useful web'apps without JavaScript?
{
}
GET
POST
PUT
DELETE
...
parses & executes files
Top
Bottom
{
}
When does this matter?
⭐ include your CSS in the <head> element
⭐ include your JS at the end of the <body>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="./style.css" />
</head>
<body>
<!-- body contents -->
<script type="text/javascript" src="./app.js"></script>
</body>
</html>
fat server
stupid client
heavy processing on the server
client just renders the page
thin server
smart client
server acts mainly as a data broker
client performs AJAX requests, then updates the UI accordingly, instead of re-rendering the entire page
extremely popular in form of SPA's { Single Page Applications }
Stupid client & fat server vs Smart client & thin server
Hmm...
#1 is in general faster to load & provides better SEO
#2 provides a much better UX { User Experience }
⭐ best way is in the middle: - serve the HTML, CSS & JavaScript upon entering the website - switch to a SPA under the hood afterwards
Interpreted or Compiled?
Translate the JavaScript code into machine language line-by-line, upon execution!
PROs
CONs
👍 instant start - great for the Web
👎 not performant
Translate the entire code into machine-code & optimize it before runtime.
PROs
CONs
👍 performance
👎 slow start 👎 must be done every time we execute
JavaScript is
function sum(x, y) {
return x + y;
}
sum(1,2);
sum(3,4);
sum(5,6);
/* ... */
{calling the sum function}
interpret the code and run it
1
interpret the code and run it
2
interpret the code and run it
3
.
.
.
hold on! This function is executed a lot with same parameter types! Can't I optimize it?
n
function sum(x, y) {
return x + y;
}
sum(1,2);
sum(3,4);
sum(5,6);
/* ... */
sum(100, 101);
{calling the sum function}
compile it! { to speed up}
n+1
when it's called with the same parameter types ⏬ run the compiled version
n+1
.
.
.
What if I call sum() with string arguments?
sum(1,2);
sum(3,4);
sum(5,6);
/* ... */
sum(100, 101);
/* ... */
sum('I love', 'You')
oups! It seems you're calling it with strings! ⏬ the compiled version was for numbers... ⏬ so I gotta throw that away & interpret it... 😞
m
.
.
.
Humans have dogs We've got devTools
🎹 F12 or Cmd + F12
<br/>
Brendan Eich
1995 JS creation
1997 ECMA standard
2007 V8 project starts
2008 - 2010 Race for speed
2009 AngularJS
2013 React
2009 NodeJS
2014 VueJS
2018 > 5B devices
Number
String
Boolean
Object
Null 😲
Undefined 😲😲
Symbol* 😲😲😲
let web;
console.log(typeof web);
web = 22;
console.log(web);
web = 'Amu is String';
⭐ for
⭐ while
⭐ if ( == vs === )
{ environment setup }
VS Code
Prettier
✅ write a basic HTML file
✅ include a JavaScript file (1)
✅ run a console.log
✅ declare a variable, in another file and log it in the (1) file
What does it print?
⭐ JavaScript runs in the same, global scope ⭐ so we can access variables & functions inbetween scripts without specific importing
ES5
ES6
ES8
...
🔥 Till next time 🔥
👩💻 Coding exercises
made with ❤ by Pava
Recap
function sum(x, y) {
return x + y;
}
name
input parameters
output value
sum(5, 15);
name
function declaration
function invocation
❗ Where can we access the declared variables?
⭐ access inside same-scope
⭐ access from inner scope to outer scope
block scope vs function scope
function goOut() {
if (weather === "sunny") {
let outfit = "light & casual";
} else {
let outfit = "light & casual + umbrella";
}
console.log(outfit);
}
function goOut() {
const outfit;
if (weather === "sunny") {
outfit = "light & casual";
} else {
outfit = "light & casual + umbrella";
}
console.log(outfit);
}
const person = {
name: 'Bob',
occupation: 'JavaScriptER',
umbrella: true
};
if (weather === 'sunny') {
person.umbrella = false;
}
function dummy() {
for(let i = 0; i< 10; i++) {
console.log(i);
}
console.log('Outside:', i);
}
👩💻 Modify the code so that line 7 prints 10
SCOPE recap
made with ❤ by Pava
Recap you say?
The prototype represents the collection of properties and methods that all instances of a certain type/class inherit.
All Array's have a sort function already defined by the language. We say that the sort function is on the Array prototype.
⭐ We can add properties/methods to the prototype... ⭐ And even delete them...
{
}
Is JavaScript multi threaded?
⭐ JavaScript is single-threaded
⭐ JavaScript is also asynchronous!
for (let i = 0; i < 10; i++ ) {
console.log(`Iteration number ${i}`);
}
console.log('Chuck Norris is a badass');
console.log('Wait, what?');
setTimeout(function textBob() {
console.log('On my way!');
}, 2000);
document
.getElementById('logo')
.addEventListener('click', textBob);
function textBob() {
console.log("On my way!");
}
A callback is a function invoked from another function which received it as a parameter.
setTimeout(textBob, 500);
document
.getElementById("logo")
.addEventEventListener("click", textBob);
callback
callback
Tamagotchi App
Build a browser simulator of the popular Tamagotchi game. In this simulator you will have to look after your new pet.
At the start of a new game you are greeted with an image, description & stats for your pet. These stats decrease on an interval configured by you.
You then can supply your pet with food or drinks, you can tell him "Go to sleep" or awake him if he's already sleeping and even play with him. All these actions influence his stats!
The pet can also send you notifications (ex: I'm hungry! Feed me)
?
made with ❤ by Pava
✅ readability: naming & indentation
✅ functionality: simplest way to the desired result
...
✅ pure functions
✅ keep style in CSS using classes
✅ validate inputs
made with ❤ by Pava
FUN #1
<br/>
FUN #2
⭐ The ability of a function to access lexical scope variables even when it is executed in a different context.
❓ How did we implement the stopAfter function?
function stopAfter(cb, nr, max) {
let count = 0;
let intervalId = setInterval(() => {
if(count < max) {
cb();
count++;
}
if(count === max) {
clearInterval(intervalId);
console.log("Stopafter says: I'm DONE!");
}
}, nr);
}
❓ Isn't it something weird here?
<br/>
FUN #3
❗ How can we have public/private data in our JavaScript code?
🎉 by using CLOSURES, of course!
function createPet(name, age) {
let pet ={
name,
age
};
return {
getName: function() {
return name;
},
getAge: function() {
return age;
},
increaseAge: function() {
pet.age++;
}
};
}
let myDog = createPet("Bob", 2);
myDog.increaseAge();
❗ But, how do I access the public API from my module?
😎 revealing module pattern to the rescue!
<br/>
FUN #4
Tamagotchi App Extend the app to dynamically add as many pets as we want!
made with ❤ by Pava
🎙 Conf's review
What the heck is the event loop anyway?
- Philip Roberts [at] JSConfEU -
<TAMAGOTCHI/>
made with ❤ by Pava
module Pattern & the intervals
innerHTML vs DOM methods
localStorage data vs pet object data
reading "state" from the DOM
selecting from the DOM every time
made with ❤ by Pava
View
⭐ I take what you give me and put on the screen
Model
⭐ I categorize and manage all our data
Controller
⭐ I make sure that these guys play together nicely and without bothering each other!
hey model!
Hey model! Uhm...smth happened sooo, you gotta update your data!
Ok, done!
Let me notify all
those interested in
the changes...
Sir sir!
The user CLICKED on something!!!
<br/>
<br/>
🎙 Conf's review
JavaScript engines - how do they even?
- Franziska Hinkelmann [at] JSConfEU -
Web performance made easy
- Addy Osmani & Eva Gasperowicz [at] Google I/O 18 -
made with ❤ by Pava
Built JS in 1995
Standardized in 1997 at ECMA
where the TC39 is responsible for the spec!
❤❤❤Everyone can contribute!!!!! ❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤
Stage 0: strawman
Stage 1: proposal
Stage 2: draft
Stage 3: candidate
Stage 4: finished
⭐ Array.prototype methods: * forEach * map * filter * some/every * reduce
- biggest change to the language in a decade -
⭐ Object.keys
1 - let && const
2 - Arrow functions && this!
3 - Default parameters
4 - Template literals
5 - Spread operator
6 - Rest operator
7 - Destructuring
😎 A more useful usecase:
8 - Classes
9 - Promises
1 - Array.prototype.includes
2 - ** operator
1 - async/await
2 - Object.values/.entries
1 - rest operator for objects
2 - spread operator for objects
1 - Stay up to date❓
2 - Check compatibility❓
made with ❤ by Pava
by Iulian
Sooooo....what ES version do we write?
💭 Thoughts on the development process...
⭐ ESLint
⭐ Prettier
Asynchronous JavaScript & XML
made with ❤ by Pava
Finishing setting up the development process
💾 npm install lite-server --save-dev
(usually spaces & new lines)
let myPet = {
name: "Bob",
age: 22
};
console.log(myPet);
let myPet={name: "Bob",age: 22};console.log(myPet);
header {
background: #000;
color: #fff;
}
header .logo {
border: 1px solid #000;
}
header{background: #000;color: #fff;}header .logo {border: 1px solid #000;}
(usually renames variables & functions)
function getSum(money) {let mySum = money.reduce(function(acc, cur) {return acc + cur;}, 0);return mySum;}
function getSum(a){var b=a.reduce(function(a,b){return a+b},0);return b}
Using the Dog.ceo API, create a gallery of dog breeds & photos.
made with ❤ by Pava
Avoid duplicate code by keeping logic that is common to different parts of the application in one place.
needs to make AJAX call
write the code & make the call
needs to make same AJAX call
write the code & make the call
⛔
Duplicate code
needs to make AJAX call
needs to make same AJAX call
create an AjaxService which has the actual code
call the service from BOTH controllers
write in the controllers just the UNIQUE, response handling code
Read
Add
Delete
Search
Edit
Login
Logout
In case you finish early:
realtime, optimized search
loading feedback
batch delete
✅ pet picture from an external API - dogs or cats ✅ or maybe avatar - adorable avatars ✅ yes-no API. It can refuse stuff! ✅ pet name from an external API - uinames
made with ❤ by Pava
The BE people have created 2 separate API's: one to check if you have permission for that video, and another to get the actual episode.
As a FE developer, integrate with their API making sure that only users with permission can watch the video
<code - callbacks/>
getPermission: function( successCb, errCb, ?force: boolean )
getVideoDetails: function( successCb, errCb, ?force: boolean )
I solemnly PROMISE that I am up to no good!
Oh oh!!!
Yet another way of handling async flows???
Let's disect the generic HTTP method we've built...
// callbacks
function buyKebab(type, successCb, errCb) {
// ...
}
buyKebab("pork", eatIt, cookForMyself);
// promises
function buyKebab(type) {
// ...
}
buyKebab("pork").then(eatIt, cookForMyself);
A Promise is an object representing the eventual completion or failure of an asynchronous operation. - MDN
A callback driven approach requires you to send what you wanna do next to the function that does the async action.
A promise driven approach doesn't! It just does the async action and then tells you if it resolved ( success) or rejected (error).
#1 pending
#2 resolved
#3 rejected
❗ Once a Promise has been resolved or rejected, it cannot be resolved or rejected again.
swal function returns a Promise
resolves
if the user clicked the confirm button or dismissed the modal
getRandomNumber().then(
resp => swal(),
err => swal()
);
Promise.resolve()
Promise.reject()
new Promise(
fn: function< function,function >
)
The BE people have created 2 separate API's: one to check if you have permission for that video, and another to get the actual episode.
As a FE developer, integrate with their API making sure that only users with permission can watch the video
<code - promises/>
getPermission: function( ?force: boolean ) @returns: Promise
getVideoDetails: function( ?force: boolean )
@returns: Promise
⭐ convert the generic HTTP method to a Promise-based one | Tamagotchi
⭐ convert the services to be Promise based | Tamagotch
made with ❤ by Pava
Promise.prototype.then and Promise.prototype.catch return a promise.
Promise.resolve(2)
.then(x => x + 2)
.then(y => y * 2)
.then(z => z * 10)
.then(final => console.log(final));
getUsers()
.then(users => users.filter(/* ... */))
.then(users => users.map(/* ... */));
getUser("bob")
.then(user => getResults(user, "js-test")
.then(results => results.filter(r => r.total > 50))
.then(/* ... */);
action1().then(resp1 => { action2(resp1).then(resp2 => { action3(resp2).then(resp3 => { console.log(resp3); }, err3 => {/* ... */}) }, err2 => {/* ... */} }, err => {/* ... */}
there's gotta be a better way!
action1()
.then(resp1 => action2(resp1))
.then(resp2 => action3(resp2))
.then(resp3 => console.log(resp3))
.catch(err => console.log("Error above"));
action1()
.then(resp1 => action2(resp1))
.then(resp2 => action3(resp2))
.catch(err => {
console.log("Error at 1 or 2");
return fallbackObj;
})
.then(resp3 => console.log(resp3))
.catch(err => console.log("Error at 3"));
Oh oh!!!
Yet another way of handling API calls???
fetch(url, options);
fetch("url")
.then(resp => console.log(resp));
fetch("url")
.then(resp => resp.json())
.then(jsonResp => console.log(jsonResp));
fetch("url")
.then(resp => resp.text())
.then(textResp=> console.log(textResp));