Complete javascript

👨‍💻 training 👩‍💻

made with ❤ by Pava

⭐ I love coding { Javascript }

⭐ Just as much as teaching it

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

FE

desktop

mobile

BE

VR/AR

📄 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

ARE YOU READY?

internet & the web

CLIENT              SERVER

  • Java
  • PHP
  • JavaScript
  • etc...
Can we have useful web'apps without JavaScript?

DEMO

{
}

HTTP Protocol

 1) HTTP methods

2) http status codes

GET
POST
PUT
DELETE
...

 3) header

 & body*

browser

parses & executes files
Top
Bottom

HTML

CSS

JS

{
}
When does this matter?

Take-away #1

⭐ 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>

architecture #1

fat server
stupid
client
  • heavy processing on the server
  • client just renders the page

architecture #2

thin server
smart
client

architecture #2

  • 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

Take-away #2

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

javascript engine

Interpreted or Compiled?

interpretors

Translate the JavaScript code into machine language line-by-line, upon execution!
PROs
CONs
👍 instant start - great for the Web
👎 not performant

Compilers

Translate the entire code into machine-code & optimize it before runtime.
PROs
CONs
👍 performance
👎 slow start

👎 must be done every time we execute

javascript engine

JavaScript is 

🔥 BOTH! 🔥

javascript engine

It uses a technique called

JIT: Just-in-time Compilation

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

.

.

.

Take-away #3

Dev tools

Humans have dogs

We've got devTools
🎹 F12 or Cmd + F12
<br/>

JavaScript

Brendan
Eich

A look at the past...

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

variables

  • Number
  • String
  • Boolean
  • Object
  • Null 😲
  • Undefined 😲😲
  • Symbol*   😲😲😲
let web;
console.log(typeof web);

web = 22;

console.log(web);

web = 'Amu is String';

CONtrol structures

⭐ 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?

Take-away #4

⭐ JavaScript runs in the same, global scope

⭐ so we can access variables & functions inbetween scripts without specific importing

JS Versions

What's up with all those words I hear?

ES5
ES6
ES8
...

🔥🚀❤let's get coding

starter

🔥 Till next time 🔥
👩‍💻 Coding exercises

Day #2

👨‍💻 complete js 👩‍💻

made with ❤ by Pava
Recap
  • ⭐ scope

  • functions

Goal

function sum(x, y) {

  return x + y;
}
name
input parameters
output
value
sum(5, 15);
name
function declaration
function invocation

SCOPE

❗ Where can we access the declared variables?

SCOPE

⭐ access inside same-scope


⭐ access from inner scope to outer scope

SCOPE

let 🥊 var

block scope   vs  function scope
function goOut() {
    if (weather === "sunny") {
        let outfit = "light & casual";
    } else {
        let outfit = "light & casual + umbrella";
    }
    
    console.log(outfit);
}

SCOPE

let || var 🥊 const

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

🔥🚀❤let's get coding

functions

🙏 Thanks!

Day #3

👨‍💻 complete js 👩‍💻

made with ❤ by Pava
Recap you say?

prototypical inheritance

prototype

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.

prototype

⭐ We can add properties/methods to the prototype...

⭐ And even delete them...

DEMO

{
}

👨‍💻👩‍💻Array prototype

prototype

Is JavaScript multi threaded?

take away #7

⭐ JavaScript is single-threaded

JavaScript is also asynchronous!

Oh oh! What is 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

callbacks

⭐ let's get coding ⭐

👨‍💻 the BIG CODE practice 👩‍💻

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)

BONUS

?

🙏 Thanks!

Day #4

👨‍💻 complete js 👩‍💻

made with ❤ by Pava

🔥 demos!!! 🔥

🔍  CODE Review  🔍

30 mins

✅ readability: naming & indentation

✅ functionality: simplest way to the desired result

...

✅ pure functions

✅ keep style in CSS using classes

✅ validate inputs

🙏 Thanks!

Day #5

👨‍💻 complete js 👩‍💻

made with ❤ by Pava
FUN #1

let's

  🚀 implement

    🔥 the feedback!

 

<br/>

CODE in the dark

FUN #2

CLOSURES

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?

⭐ let's get coding ⭐

CLOSURES

<br/>

left-hand

coding

FUN #3

⭐ let's get coding #2 ⭐

CLOSURES

module pattern

❗ 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!

⭐ let's get coding ⭐

module pattern

<br/>

all for one

one for all

FUN #4

tamagochi

⭐ let's add support for 2 pets ⭐

👨‍💻 till next time  👩‍💻

Tamagotchi App

Extend the app to dynamically add as many pets as we want!

🙏 Thanks!

Day #6

👨‍💻 complete js 👩‍💻

made with ❤ by Pava

all for one

one for all

🎙 Conf's review
What the heck is the event loop anyway?
- Philip Roberts [at] JSConfEU -
<TAMAGOTCHI/>

🙏 Thanks!

Day #7

👨‍💻 complete js 👩‍💻

made with ❤ by Pava

😞 Most common mistakes...

  • 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

let's

  🚀 implement

    🔥 the feedback!

 

Model

view

ctrl

📢

MVC practice

🙏 Thanks!

Day #8

👨‍💻 complete js 👩‍💻

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!!!

 - MVC practice -

Picture organizer ⭐

all for one

one for all

<br/>

Tamagotchi

+

MVC

=

💖💖💖

<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 -

Day #10

👨‍💻 complete js 👩‍💻

made with ❤ by Pava

🚀 ES5, ES6 & beyond!

Built JS
in 1995
Standardized in 1997 at ECMA
where the TC39 is responsible for the spec!

❤❤❤Everyone can contribute!!!!! ❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤

4 Stages from 💡 to ❤

  • Stage 0: strawman
  • Stage 1: proposal
  • Stage 2: draft
  • Stage 3: candidate
  • Stage 4: finished

ES5 / Es2009

 Array.prototype methods:

* forEach
* map
* filter
* some/every
* reduce

- biggest change to the language in a decade -
 Object.keys

ES6 / Es2015

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

ES7 / Es2016

1 - Array.prototype.includes
2 - ** operator

ES8 / Es2017

1 - async/await
2 - Object.values/.entries

ES9 / Es2018

1 - rest operator for objects
2 - spread operator for objects

How do i...

1 - Stay up to date❓
2 - Check compatibility❓

🔥 es.next your code 🔥

Day #11

👨‍💻 complete js 👩‍💻

made with ❤ by Pava
by Iulian

🐷 Piggy Bank Hack

👉 back to es.next...

Sooooo....what ES version do we write?
💭 Thoughts on the development process...

<Tools />

⭐ ESLint

 

⭐ Prettier

<br />

AJAX!

Asynchronous JavaScript & XML

🎉 Practice

🙏 Thanks!

Day #12

👨‍💻 complete js 👩‍💻

made with ❤ by Pava
Finishing setting up the development process

#1 finishing our build setup

#2 AJAX

0 - server

💾 npm install lite-server --save-dev

1 - MINIFY

Removes all redundant characters from our source files

(usually spaces & new lines)
let myPet =  { 
    name: "Bob",
    age: 22
};

console.log(myPet);
let myPet={name: "Bob",age: 22};console.log(myPet);

30% saved

header {
    background: #000;
    color: #fff;
}
header .logo {
    border: 1px solid #000;
}
header{background: #000;color: #fff;}header .logo {border: 1px solid #000;}

25% saved

2 - uglify

transpiles our code to a smaller but equivalent one

(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}

38% saved

3 - source-maps

creates a mapping between the resulted, uglified code, and the original one so that we can easily debug

<br />

WEB

#2 AJAX

  1. Recap

  2. POSTMAN

  3. Exercises

AJAX exercise #1

Using the Dog.ceo API, create a gallery of dog breeds & photos.

AJAX exercise #2

🐶 AJAX PETS 🐱‍👤

🙏 Thanks!

Day #13

👨‍💻 complete js 👩‍💻

made with ❤ by Pava

🍕 Services

Avoid duplicate code by keeping logic that is common to different parts of the application in one place.

MVC usecase

Controller 1

👎 Without Services

needs to make AJAX call
write the code & make the call

Controller 2

needs to make same AJAX call
write the code & make the call
⛔ 
Duplicate code

Controller 1

👍 With Services

needs to make AJAX call

Controller 2

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

🐶 AJAX-PETS 🐱‍👤

  • Read
  • Add
  • Delete
  • Search
  • Edit  
  • Login
  • Logout

Phase #1

Phase #2

Phase #3

CORS!

😡 Backend's fault ❗❗❗

In case you finish early:
  • realtime, optimized search
  • loading feedback
  • batch delete

<br />

TAMAGOTCHI!!!

✅ 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

🙏 Thanks!

Day #14

👨‍💻 complete js 👩‍💻

made with ❤ by Pava

NETFLIX simulator

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).

A Promise can be in one of 3 states:

#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

Get random number as a Promise

<br />

How do we create a Promise ❓

getRandomNumber().then(
    resp => swal(),
    err => swal()
);
Promise.resolve()
Promise.reject()
new Promise(
    fn: function< function,function >
)

Practice

<br />

NETFLIX simulator

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 

To Practice:

 convert the generic HTTP method to a Promise-based one | Tamagotchi
 convert the services to be Promise based | Tamagotch

🙏 Thanks!

Day #15

👨‍💻 complete js 👩‍💻

made with ❤ by Pava

Promise chaining

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(/* ... */);

err handling

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"));

or...

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"));

Promise chaining

🎉 practice 🎉

Promise.all

<BR />

Oh oh!!!
Yet another way of handling API calls??? 

fetch

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));

to the code

🙏 Thanks!