Thanks to visit codestin.com
Credit goes to www.slideshare.net

slides for
theory lectures
(DON’T SKIP THEM, THEY ARE SUPER
IMPORTANT 🤓)
Subscribe here
Follow me here
📖 TABLE OF CONTENTS: THEORY LECTURES (CLICK THE TITLES)
Watch before you start!
A Brief Introduction to JavaScript
Data Types
Boolean Logic
JavaScript Releases: ES5, ES6+ and ESNext
Functions Calling Other Functions
Reviewing Functions
Learning How to Code
How to Think Like a Developer
Debugging (Fixing Errors)
What's the DOM and DOM Manipulation
An high-level Overview of JavaScript
The JavaScript Engine and Runtime
Execution Contexts and The Call Stack
Scope and The Scope Chain
Variable environment: Hoisting and The TDZ
The this Keyword
Primitives vs. Objects (Primitive vs. Reference Types)
Summary: Which Data Structure to Use?
First-Class and Higher-Order Functions
Closures
Data Transformations: map, filter, reduce
Summary: Which Array Method to Use?
How the DOM Really Works
Event Propagation: Bubbling and Capturing
Efficient Script Loading: defer and async
What is Object-Oriented Programming?
OOP in JavaScript
Prototypal Inheritance and The Prototype Chain
Object.create
Inheritance Between "Classes": Constructor Functions
Inheritance Between "Classes": Object.create
ES6 Classes summary
Mapty Project: How to Plan a Web Project
Mapty Project: Final Considerations
Asynchronous JavaScript, AJAX and APIs
How the Web Works: Requests and Responses
Promises and the Fetch API
Asynchronous Behind the Scenes: The Event Loop
An Overview of Modern JavaScript Development
An Overview of Modules in JavaScript
Modern, Clean and Declarative JavaScript Programming
Forkify: Project Overview and Planning
The MVC Architecture
Event Handlers in MVC: Publisher-Subscriber Pattern
Forkify Project: Final Considerations
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
WELCOME, WELCOME,
WELCOME!
SECTION
LECTURE
WELCOME, WELCOME, WELCOME!
WATCH BEFORE YOU START!
SOME QUICK CONSIDERATIONS BEFORE WE START... 🚀
✌ This course is for all of you! So please don’t write a bad review right away if the course is too easy, or too hard, or
progressing too slow, or too fast for you. To make it perfect for YOU, you can rewatch lectures, jump to other sections,
watch the course with slower or faster playback speed, or ask questions.
Please don’t be that person.
Everyone is different…
(Unless the course itself is truly terrible)
SOME QUICK CONSIDERATIONS BEFORE WE START... 🚀
👩💻 You need to code along with me! You will learn ZERO JavaScript skills by just sitting and watching me code. You have to
code YOURSELF!
SOME QUICK CONSIDERATIONS BEFORE WE START... 🚀
🤓 Try all the coding challenges! Try to do your best, but if you get stuck for too long, watch the solution. Don’t beat yourself
up if you can’t figure it out! Just rewatch the lectures that were covered in the challenge, try to understand them better,
and move on.
Watch for this sign!
SOME QUICK CONSIDERATIONS BEFORE WE START... 🚀
📝 If you want the course material to stick, take notes. Notes on code syntax, notes on theory concepts, notes on everything!
Totally non-coding... Try to
understand a single word 😂
SOME QUICK CONSIDERATIONS BEFORE WE START... 🚀
😱 If this is your first time ever programming, please don’t get overwhelmed. It’s 100% normal that you will not understand
everything at the beginning. Just don’t think “I guess coding is not for me”!
SOME QUICK CONSIDERATIONS BEFORE WE START... 🚀
😅 In the first sections of the course, don’t bother understanding WHY things work the way they do in JavaScript. Also, don’t
stress about efficient code, or fast code, or clean code. While learning, we just want to make things WORK. We will
understand the WHY later in the course.
SOME QUICK CONSIDERATIONS BEFORE WE START... 🚀
⏳ Before moving on from a section, make sure that you understand exactly what was covered. Take a break, review the code
we wrote, review your notes, review the projects we built, and maybe even write some code yourself.
✅ ✅ ✅
SOME QUICK CONSIDERATIONS BEFORE WE START... 🚀
⁉ If you have an error or a question, start by trying to solve it yourself! This is essential for your progress. If you can’t solve
it, check the Q&A section. If that doesn’t help, just ask a new question. Use a short description, and post relevant code.
1
2
3
😲
SOME QUICK CONSIDERATIONS BEFORE WE START... 🚀
🖥 I recorded this course on a Mac, but everything works the exact same way on Windows or Linux. If something doesn’t
work on your computer, it’s NOT because you’re using a different OS.
SOME QUICK CONSIDERATIONS BEFORE WE START... 🚀
😍 Most importantly, have fun! It’s so rewarding to see something that YOU have built YOURSELF! So if you’re feeling
frustrated, stop whatever you’re doing, and come back later!
And I mean REAL fun 😅
JAVASCRIPT
FUNDAMENTALS –
PART 1
SECTION
LECTURE
JAVASCRIPT FUNDAMENTALS – PART 1
A BRIEF INTRODUCTION TO
JAVASCRIPT
WHAT IS JAVASCRIPT?
JAVASCRIPT IS A HIGH-LEVEL,
OBJECT-ORIENTED, MULTI-PARADIGM
PROGRAMMING LANGUAGE.
JAVASCRIPT
🤯
Instruct computer to do things
We don’t have to worry about complex
stuff like memory management
We can use different styles
of programming
Based on objects, for
storing most kinds of data
NOUNS
THE ROLE OF JAVASCRIPT IN WEB DEVELOPMENT
CONTENT
PRESENTATION PROGRAMMING LANGUAGE:
BUILDING WEB APPLICATIONS
p {color: red}
means “the
paragraph text is red”
<p></p>
means “paragraph”
VERBS
p.hide();
means “hide the
paragraph”
ADJECTIVES
EXAMPLE OF DYNAMIC EFFECTS / WEB APPLICATION
Show spinner + loading
data in the background
Show data after loading
Display user info on
hover
Show spinner + loading
data in the background
Display tweets after
loading data
Show tweet box
after clicking
THIS COURSE
THERE IS NOTHING YOU CAN’T DO WITH JAVASCRIPT (WELL, ALMOST…)
Dynamic effects and
web applications in the
browser 😍
Web applications on
web servers
Native mobile
applications
Native desktop
applications
100% based on JavaScript. They might
go away, but JavaScript won’t!
Back-end apps
Front-end apps
JAVASCRIPT RELEASES... (MORE ABOUT THIS LATER)
ES5
ES6/
ES2015
ES7/
ES2016
ES8/
ES2017
ES9/
ES2018
ES10/
ES2019
...
Biggest update to the
language EVER
New updates to JS
every single year
ES11/
ES2020
...
🔥 Learn modern JavaScript from the beginning, but without forgetting the older parts!
🥳 Let’s finally get started!
ECMAScript
Modern JavaScript
SECTION
LECTURE
JAVASCRIPT FUNDAMENTALS – PART 1
DATA TYPES
OBJECTS AND PRIMITIVES
VALUE
OBJECT PRIMITIVE
EVERYTHING ELSE
OR
THE 7 PRIMITIVE DATA TYPES
1. Number: Floating point numbers 👉 Used for decimals and integers
2. String: Sequence of characters 👉 Used for text
3. Boolean: Logical type that can only be true or false 👉 Used for taking decisions
4. Undefined: Value taken by a variable that is not yet de
fi
ned (‘empty value’)
5. Null: Also means ‘empty value’
6. Symbol (ES2015): Value that is unique and cannot be changed [Not useful for now]
7. BigInt (ES2020): Larger integers than the Number type can hold
☝ JavaScript has dynamic typing: We do not have to manually de
fi
ne the data type of
the value stored in a variable. Instead, data types are determined automatically.
Value has type, NOT variable!
SECTION
LECTURE
JAVASCRIPT FUNDAMENTALS – PART 1
BOOLEAN LOGIC
A OR B
“Sarah has a driver’s license
OR good vision”
OR TRUE FALSE
TRUE TRUE TRUE
FALSE TRUE FALSE
A
B
BASIC BOOLEAN LOGIC: THE AND, OR & NOT OPERATORS
AND TRUE FALSE
TRUE TRUE FALSE
FALSE FALSE FALSE
A
B
A AND B
“Sarah has a driver’s license
AND good vision”
true when ALL are true
👇
true when ONE is true
👇
No matter how many variables
NOT A, NOT B
Inverts true/false value
👇
A: Sarah has a driver’s license
B: Sarah has good vision
👉 EXAMPLE:
Boolean variables that can
be either TRUE or FALSE
Possible values
Results of
operation,
depending on
2 variables
AN EXAMPLE 👩💻
👉 A: Age is greater or equal 20
👉 B: Age is less than 30
OR TRUE FALSE
TRUE TRUE TRUE
FALSE TRUE FALSE
A
B
AND TRUE FALSE
TRUE TRUE FALSE
FALSE FALSE FALSE
A
B
false
true
age = 16
BOOLEAN VARIABLES
LET’S USE OPERATORS!
👉 !A
👉 A AND B
👉 A OR B
👉 !A AND B
👉 A OR !B
true
false
true
true
false
false true
false true
true
true
false
false false
SECTION
LECTURE
JAVASCRIPT FUNDAMENTALS – PART 1
JAVASCRIPT RELEASES: ES5, ES6+
AND ESNEXT
A BRIEF HISTORY OF JAVASCRIPT
1995 👉 Brendan Eich creates the very first version of JavaScript in just 10 days. It was called
Mocha, but already had many fundamental features of modern JavaScript!
👉 Mocha changes to LiveScript and then to JavaScript, in order to attract Java developers.
However, JavaScript has almost nothing to do with Java ☝
👉 Microsoft launches IE, copying JavaScript from Netscape and calling it JScript;
👉 With a need to standardize the language, ECMA releases ECMAScript 1 (ES1), the
fi
rst official
standard for JavaScript (ECMAScript is the standard, JavaScript the language in practice);
👉 ES5 (ECMAScript 5) is released with lots of great new features;
👉 ES6/ES2015 (ECMAScript 2015) was released: the biggest update to the language ever!
👉 ECMAScript changes to an annual release cycle in order to ship less features per update 🙏
👉 Release of ES2016 / ES2017 / ES2018 / ES2019 / ES2020 / ES2021 / … / ES2089 😅
1996
1997
2009
2015
2016 – ∞
BACKWARDS COMPATIBILITY: DON’T BREAK THE WEB!
1997
Modern JavaScript
Engine
2020
👍
BACKWARDS
COMPATIBLE
😂
Modern JavaScript
Engine
2020 2089
👎
NOT FORWARDS
COMPATIBLE
DON’T BREAK THE WEB!
👉 Old features are never removed;
👉 Not really new versions, just
incremental updates (releases)
👉 Websites keep working forever!
HOW TO USE MODERN JAVASCRIPT TODAY
👉 Fully supported in all browsers (down to IE 9 from 2011);
👉 Ready to be used today 👍
ES5
👉 ES6+: Well supported in all modern browsers;
👉 No support in older browsers;
👉 Can use most features in production with transpiling and polyfilling 😃
ES6/ES2015
↓
ES2020
👉 ESNext: Future versions of the language (new feature proposals that reach Stage 4);
👉 Can already use some features in production with transpiling and polyfilling.
ES2021 – ∞
http://kangax.github.io/compat-table
(As of 2020)
👩💻 During development: Simply use the latest Google Chrome!
🚀 During production: Use Babel to transpile and poly
fi
ll your code (converting
back to ES5 to ensure browser compatibility for all users).
Will add new videos
3 reasons why we should not forget the Good Ol’ JavaScript:
MODERN JAVASCRIPT FROM THE BEGINNING
👉 You will better understand how JavaScript actually works;
👉 Many tutorials and code you
fi
nd online today are still in ES5;
👉 When working on old codebases, these will be written in ES5.
🔥 Learn modern JavaScript from the beginning!
☝ But, also learn how some things used to be done before modern JavaScript
(e.g. const & let vs var and function constructors vs ES6 class).
JAVASCRIPT
FUNDAMENTALS –
PART 2
SECTION
LECTURE
JAVASCRIPT FUNDAMENTALS – PART 2
FUNCTIONS CALLING OTHER
FUNCTIONS
CALLING A FUNCTION INSIDE A FUNCTION: DATA FLOW
2
2
2
2
8
8
8
3
SECTION
LECTURE
JAVASCRIPT FUNDAMENTALS – PART 2
REVIEWING FUNCTIONS
FUNCTIONS REVIEW; 3 DIFFERENT FUNCTION TYPES
👉 Function declaration
Function that can be
used before it’s declared
👉 Function expression
Essentially a function
value stored in a variable
👉 Arrow function
Great for a quick one-line
functions. Has no this
keyword (more later...)
☝ Three different ways of writing functions, but they all work in a
similar way: receive input data, transform data, and then output data.
FUNCTIONS REVIEW: ANATOMY OF A FUNCTION
Arguments: actual values
of function parameters, to
input data
Variable to save returned
value (function output)
Calling, running or invoking
the function, using ()
return statement to
output a value from
the function and
terminate execution
Parameters: placeholders to receive input
values. Like local variables of a function
Function body: block of code that
we want to reuse. Processes the
function’s input data
Function name
DEVELOPER SKILLS &
EDITOR SETUP
SECTION
LECTURE
DEVELOPER SKILLS & EDITOR SETUP
LEARNING HOW TO CODE
HOW TO FAIL 🤦 AT LEARNING HOW TO CODE
💥 He didn’t have a clear goal at the beginning of his journey
💥 He started by watching courses and reading tutorials, but he would just copy the
code without caring how it works. Sometimes he would just copy and paste code!
💥 He didn’t reinforce what he was learning by doing small challenges or taking notes
💥 He didn’t practice coding, and didn’t come up with his own project ideas
💥 He quickly became frustrated when his code was not perfectly clean or efficient
💥 He lost motivation because he thought he could never know everything
💥 He was learning in isolation
💥 After finishing a couple of courses, he thought he now was a web developer and
could start applying to jobs. But he couldn’t even build an app on his own!
John
(not actually…)
HOW TO SUCCEED 🎉 AT LEARNING HOW TO CODE
💥 He would just copy the code
without caring how it works.
Sometimes he would just
copy and paste code!
👍 Understand the code that
you’re studying and typing
👍 Always type the code, don’t
copy-paste!
💥 He didn’t reinforce what he
was learning by doing small
challenges or taking notes
FIX
💥 He didn’t have a clear goal at
the beginning of his journey
👍 Set a specific, measurable,
realistic and time-based goal
👍 Know exactly why you are
learning to code: Switching
careers? Finding a better job?
👍 Imagine a big project you
want to be able to build!
👍 Research technologies you
need and then learn them
FIX
👍 After you learn a new feature
or concept, use it immediately
👍 Take notes
👍 Challenge yourself and
practice with small coding
exercises and challenges
👍 Don’t be in a hurry to
complete the course fast!
FIX
HOW TO SUCCEED 🎉 AT LEARNING HOW TO CODE
💥 He didn’t practice coding, and
didn’t come up with his own
project ideas
FIX
👍 Practicing on your own is the
most important thing to do
👍 This is NOT optional! Without
practice outside of courses,
you won’t go anywhere!
👍 Come up with your own
project ideas or copy popular
sites or applications, or just
parts of them in the beginning
👍 Don’t be stuck in “tutorial hell”
💥 He lost motivation because he
thought he could never know
everything
FIX
👍 Embrace the fact that you will
never you know everything
👍 Just focus on what you need
to achieve your goal!
💥 He quickly became frustrated
when his code was not
perfectly clean or efficient
FIX
👍 Don’t get stuck trying to write
the perfect code!
👍 Just write tons of code, no
matter the quality!
👍 Clean and efficient code will
come with time
👍 You can always refactor code
later
HOW TO SUCCEED 🎉 AT LEARNING HOW TO CODE
💥 After finishing a couple of
courses, he thought he now
was a web developer and
could start applying to jobs
FIX
👍 The biggest misconception
that people have!
👍 Courses are an amazing
starting point, but are only the
beginning of your journey!
💥 He was learning in isolation
FIX
👍 Explain new concepts to other
people. If you can explain it,
you truly understand it!
👍 Share your goals to make
yourself accountable
👍 Share your learning progress
with the web dev community
(#100DaysOfCode,
#CodeNewbie, #webdev, etc.)
NEXT SLIDE
LEARNING HOW TO CODE IS HARD, BUT YOU CAN DO IT!
Source: https://www.thinkful.com/blog/why-learning-to-code-is-so-damn-hard/
Study courses: understand code, take
challenges and notes
Stay motivated! Keep writing lots of
code on your own, no matter how bad
Learn with other people, devs and
beginners, and share progress
Keep challenging yourself, run into lots
of problems, and fix them
Round up your skillset with best
practices and tools (git, testing, …)
JOB READY
(But the learning never stops 😅)
Cliff of
confusion
Back to
awesome
Pit of
despair
Competence
Confidence
JOB READY
Everything
is awesome
You’re probably
somewhere here
SECTION
LECTURE
DEVELOPER SKILLS & EDITOR SETUP
HOW TO THINK LIKE A DEVELOPER:
BECOME A PROBLEM SOLVER!
HOW TO FAIL 🤦 AT SOLVING PROBLEMS
💥 He jumps at the problem without much thinking
💥 He implements his solution in an unstructured way
💥 He gets stressed out when things don’t work
💥 He is too proud to research solutions
John can
code now 😁
FIX
👍 Stay calm and slow down, don’t just jump at a problem without a plan
👍 Take a very logical and rational approach (programming is just logic, in the end…)
👍 Use my 4-step framework to solve any problem
NEXT SLIDE
WHENEVER JOHN ENCOUNTERS A PROBLEM:
👉 Example: In an array of
GPS coordinates,
fi
nd
the two closest points
4 STEPS TO SOLVE ANY PROBLEM
Make sure you 100% understand the
problem. Ask the right questions to get
a clear picture of the problem
1
EXAMPLE
💬 Project Manager: “We need a function
that reverses whatever we pass into it”
👉 What does “whatever” even mean in this context?
What should be reversed? Answer: Only strings,
numbers, and arrays make sense to reverse...
👉 What to do if something else is passed in?
👉 What should be returned? Should it always be a
string, or should the type be the same as passed in?
👉 How to recognize whether the argument is a number,
a string, or an array?
👉 How to reverse a number, a string, and an array?
1
4 STEPS TO SOLVE ANY PROBLEM
Make sure you 100% understand the
problem. Ask the right questions to get
a clear picture of the problem
1
Divide and conquer: Break a big
problem into smaller sub-problems.
2
EXAMPLE
💬 Project Manager: “We need a function
that reverses whatever we pass into it”
👉 Check if argument is a number, a string, or an array
👉 Implement reversing a number
👉 Implement reversing a string
👉 Implement reversing an array
👉 Return reversed value
2 SUB-PROBLEMS:
Looks like a task list that we
need to implement
4 STEPS TO SOLVE ANY PROBLEM
Make sure you 100% understand the
problem. Ask the right questions to get
a clear picture of the problem
1
Divide and conquer: Break a big
problem into smaller sub-problems.
2
EXAMPLE
💬 Project Manager: “We need a function
that reverses whatever we pass into it”
👉 How to check if a value is a number in JavaScript?
👉 How to check if a value is a string in JavaScript?
👉 How to check if a value is an array in JavaScript?
👉 How to reverse a number in JavaScript?
👉 How to reverse a string in JavaScript?
👉 How to reverse an array in JavaScript?
3
Don't be afraid to do as much
research as you have to
3
4 STEPS TO SOLVE ANY PROBLEM
Make sure you 100% understand the
problem. Ask the right questions to get
a clear picture of the problem
1
Divide and conquer: Break a big
problem into smaller sub-problems.
2
EXAMPLE
💬 Project Manager: “We need a function
that reverses whatever we pass into it”
4
Don't be afraid to do as much
research as you have to
3
For bigger problems, write pseudo-code
before writing the actual code
4
function reverse(value)
if value type !string && !number && !array
return value
if value type == string
reverse string
if value type == number
reverse number
if value type == array
reverse array
return reversed value
SECTION
LECTURE
DEVELOPER SKILLS & EDITOR SETUP
DEBUGGING (FIXING ERRORS)
WHAT IS A SOFTWARE BUG?
👉 Software bug: Defect or problem in a computer program.
Basically, any unexpected or unintended behavior of a
computer program is a software bug.
👉 Bugs are completely normal in software development!
👉 Previous example: “We need a function that reverses whatever
we pass into it”
reverse([1, 3, 5, 7])
[5, 1, 7, 3]
👉 Debugging: Process of finding, fixing and preventing bugs.
Unexpected result: the array
is scrambled, NOT reversed.
So there is a bug in the
reverse function 🐛
A real bug which was
causing an error in Harvard’s
computer in the 1940s
THE DEBUGGING PROCESS
IDENTIFY
Becoming aware
that there is a bug
👉 During development
👉 Testing software
👉 User reports during
production
👉 Context: browsers,
users, etc.
FIND
Isolating where
exactly the bug is
happening in code
FIX
Correct the bug
PREVENT
Preventing it from
happening again
👉 Searching for the
same bug in similar
code
👉 Writing tests using
testing software
👉 Developer console
(simple code)
👉 Debugger (complex
code)
👉 Replace wrong
solution with new
correct solution
JAVASCRIPT IN THE
BROWSER: DOM AND
EVENTS
FUNDAMENTALS
SECTION
LECTURE
JAVASCRIPT IN THE BROWSER: DOM
AND EVENTS FUNDAMENTALS
WHAT'S THE DOM AND DOM
MANIPULATION
WHAT IS THE DOM?
DOCUMENT OBJECT MODEL: STRUCTURED
REPRESENTATION OF HTML DOCUMENTS. ALLOWS
JAVASCRIPT TO ACCESS HTML ELEMENTS AND
STYLES TO MANIPULATE THEM.
DOM
Change text, HTML attributes,
and even CSS styles
Tree structure, generated
by browser on HTML load
THE DOM TREE STRUCTURE
Special object that is the entry
point to the DOM. Example:
document.querySelector()
WEB APIs DOM Methods and
Properties
DOM !=
=JAVASCRIPT 🧐
DOM Methods and
Properties for DOM
Manipulation
👎
NOT PART OF
For example
document.querySelector()
Timers
Fetch
👍
CAN INTERACT
WITH
API: Application Programming Interface
HOW JAVASCRIPT
WORKS BEHIND THE
SCENES
SECTION
LECTURE
HOW JAVASCRIPT WORKS BEHIND THE
SCENES
AN HIGH-LEVEL OVERVIEW OF
JAVASCRIPT
WHAT IS JAVASCRIPT: REVISITED
JAVASCRIPT IS A HIGH-LEVEL,
OBJECT-ORIENTED, MULTI-PARADIGM
PROGRAMMING LANGUAGE.
JAVASCRIPT
WHAT IS JAVASCRIPT: REVISITED
JAVASCRIPT IS A HIGH-LEVEL, PROTOTYPE-BASED OBJECT-ORIENTED,
MULTI-PARADIGM, INTERPRETED OR JUST-IN-TIME COMPILED,
DYNAMIC, SINGLE-THREADED, GARBAGE-COLLECTED PROGRAMMING
LANGUAGE WITH FIRST-CLASS FUNCTIONS AND A NON-BLOCKING
EVENT LOOP CONCURRENCY MODEL.
JAVASCRIPT
🤔 🤯 🤣
DECONSTRUCTING THE MONSTER DEFINITION
High-level
Prototype-based object-oriented
Multi-paradigm
Interpreted or just-in-time compiled
Dynamic
Single-threaded
Garbage-collected
First-class functions
Non-blocking event loop
High-level
Prototype-based object-oriented
Multi-paradigm
Interpreted or just-in-time compiled
Dynamic
Single-threaded
Garbage-collected
First-class functions
Non-blocking event loop
+
👉 Any computer program needs resources:
LOW-LEVEL
Developer has to manage
resources manually
HIGH-LEVEL
Developer does NOT have
to worry, everything
happens automatically
DECONSTRUCTING THE MONSTER DEFINITION
High-level
Prototype-based object-oriented
Multi-paradigm
Interpreted or just-in-time compiled
Dynamic
Single-threaded
Garbage-collected
First-class functions
Non-blocking event loop
🧹
✨ Cleaning the memory
so we don’t have to
DECONSTRUCTING THE MONSTER DEFINITION
High-level
Prototype-based object-oriented
Multi-paradigm
Interpreted or just-in-time compiled
Dynamic
Single-threaded
Garbage-collected
First-class functions
Non-blocking event loop
Abstraction over
0s and 1s
More about this Later in this Section 👇
CONVERT TO MACHINE CODE = COMPILING
DECONSTRUCTING THE MONSTER DEFINITION
Happens inside the
JavaScript engine
High-level
Prototype-based object-oriented
Multi-paradigm
Interpreted or just-in-time compiled
Dynamic
Single-threaded
Garbage-collected
First-class functions
Non-blocking event loop
DECONSTRUCTING THE MONSTER DEFINITION
More about this later in Multiple Sections 👉
👉 Paradigm: An approach and mindset of structuring code, which will
direct your coding style and technique.
1 Procedural programming
2 Object-oriented programming (OOP)
3 Functional programming (FP)
The one we’ve been
using so far
☝ Imperative vs.
👋 Declarative
High-level
Prototype-based object-oriented
Multi-paradigm
Interpreted or just-in-time compiled
Dynamic
Single-threaded
Garbage-collected
First-class functions
Non-blocking event loop
DECONSTRUCTING THE MONSTER DEFINITION
Our array
inherits methods
from prototype
Array.prototype.push
Array.prototype.indexOf
Built from prototype
Array
Prototype
More about this in Section Object Oriented Programming 👉
(Oversimplification!)
High-level
Prototype-based object-oriented
Multi-paradigm
Interpreted or just-in-time compiled
Dynamic
Single-threaded
Garbage-collected
First-class functions
Non-blocking event loop
More about this in Section A Closer Look at Functions 👉
👉 In a language with first-class functions, functions are simply treated
as variables. We can pass them into other functions, and return them
from functions.
Passing a function into another
function as an argument:
First-class functions!
DECONSTRUCTING THE MONSTER DEFINITION
High-level
Prototype-based object-oriented
Multi-paradigm
Interpreted or just-in-time compiled
Dynamic
Single-threaded
Garbage-collected
First-class functions
Non-blocking event loop
No data type definitions. Types
becomes known at runtime
Data type of variable is
automatically changed
👉 Dynamically-typed language:
DECONSTRUCTING THE MONSTER DEFINITION
High-level
Prototype-based object-oriented
Multi-paradigm
Interpreted or just-in-time compiled
Dynamic
Single-threaded
Garbage-collected
First-class functions
Non-blocking event loop
DECONSTRUCTING THE MONSTER DEFINITION
👉 Concurrency model: how the JavaScript engine handles multiple tasks
happening at the same time.
Why do we need that?
👉 JavaScript runs in one single thread, so it can only do one thing at a time.
👉 Sounds like it would block the single thread. However, we want non-blocking
behavior!
So what about a long-running task?
👉 By using an event loop: takes long running tasks, executes them in the
“background”, and puts them back in the main thread once they are
fi
nished.
How do we achieve that?
More about this Later in this Section 👇
(Oversimplification!)
SECTION
LECTURE
HOW JAVASCRIPT WORKS BEHIND THE
SCENES
THE JAVASCRIPT ENGINE AND
RUNTIME
WHAT IS A JAVASCRIPT ENGINE?
PROGRAM THAT EXECUTES
JAVASCRIPT CODE.
JS ENGINE ENGINE
👉 Example: V8 Engine
CALL STACK HEAP
Object in
memory
Execution
context
Where our code
is executed
Where objects
are stored
How is it
compiled?
👉 Interpretation: Interpreter runs through the source code and executes it line by line.
COMPUTER SCIENCE SIDENOTE: COMPILATION VS. INTERPRETATION 🤓
👉 Compilation: Entire code is converted into machine code at once, and written to a binary
fi
le that can be executed by a computer.
Portable file:
machine code
Source code
STEP 1
COMPILATION
Program
running
STEP 2
EXECUTION
Source code
STEP 1
EXECUTION LINE BY LINE
Program
running
Can happen way after compilation
Code still needs to be converted to machine code
Machine code
Source code
STEP 1
COMPILATION
Program
running
STEP 2
EXECUTION
Happens immediately
👉 Just-in-time (JIT) compilation: Entire code is converted into machine code at once, then executed immediately.
NOT a portable file
Optimization
MODERN JUST-IN-TIME COMPILATION OF JAVASCRIPT
Compilation
Execution
Parsing
AST
Example
👉 AST Example
Happens in
Call Stack
ENGINE
Just-in-time
compilation
Happens in special
threads that we can’t
access from code
During execution!
“JavaScript is an
interpreted language”
RUNTIME IN THE BROWSER
THE BIGGER PICTURE: JAVASCRIPT RUNTIME
ENGINE
HEAP CALL STACK
CALLBACK QUEUE
timer data ...
EVENT LOOP
WEB APIs
DOM Timers
Fetch API ...
Container including all the things
that we need to use JavaScript
(in this case in the browser)
Example: Callback function from DOM event listener
Essential for non-blocking concurrency model
onClick
click
Functionalities provided to
the engine, accessible on
window object
RUNTIME IN NODE.JS
ENGINE
HEAP CALL STACK
THE BIGGER PICTURE: JAVASCRIPT RUNTIME
CALLBACK QUEUE
timer data ...
EVENT LOOP
WEB APIs
click
C++ BINDINGS &
THREAD POOL
SECTION
LECTURE
HOW JAVASCRIPT WORKS BEHIND THE
SCENES
EXECUTION CONTEXTS AND THE
CALL STACK
EXECUTION
Compilation
WHAT IS AN EXECUTION CONTEXT?
Creation of global execution
context (for top-level code)
Execution of top-level code
(inside global EC)
Execution of functions and
waiting for callbacks
Example: click event callback
NOT inside
a function
👉 Human-readable code:
Function body
only executed
when called!
Environment in which a piece of JavaScript
is executed. Stores all the necessary
information for some code to be executed.
EXECUTION CONTEXT
👉 Exactly one global execution context (EC):
Default context, created for code that is not
inside any function (top-level).
🍕
📦 🍴 🧾
+ +
👉 One execution context per function: For each
function call, a new execution context is created.
Pizza “execution context”
“JavaScript code"
All together make the call stack
second()
first()
Global
EXECUTION CONTEXT IN DETAIL
WHAT’S INSIDE EXECUTION CONTEXT?
👉 let, const and var declarations
👉 Functions
👉 arguments object
1 Variable Environment
2 Scope chain
3 this keyword
Generated during “creation
phase”, right before execution
NOT in arrow
functions!
a = 1
b = <unknown>
c = 2
arguments = [7, 9]
name = ‘Jonas’
first = <function>
second = <function>
x = <unknown>
Array of passed arguments. Available
in all “regular” functions (not arrow)
Need to run
second() first
Need to run
first() first
Literally the
function code
(Technically, values
only become known
during execution)
ENGINE
CALL STACK
THE CALL STACK
👉 Compiled code starts execution
first()
second()
Global
“Place” where execution contexts get
stacked on top of each other, to keep
track of where we are in the execution
🗺
SECTION
LECTURE
HOW JAVASCRIPT WORKS BEHIND THE
SCENES
SCOPE AND THE SCOPE CHAIN
SCOPING AND SCOPE IN JAVASCRIPT: CONCEPTS
👉 Scoping: How our program’s variables are organized and accessed. “Where do variables
live?” or “Where can we access a certain variable, and where not?”;
👉 Lexical scoping: Scoping is controlled by placement of functions and blocks in the code;
👉 Scope: Space or environment in which a certain variable is declared (variable
environment in case of functions). There is global scope, function scope, and block scope;
👉 Scope of a variable: Region of our code where a certain variable can be accessed.
SCOPE CONCEPTS
👉 Variable environment
👉 Scope chain
👉 this keyword
EXECUTION CONTEXT
THE 3 TYPES OF SCOPE
FUNCTION SCOPE
GLOBAL SCOPE BLOCK SCOPE (ES6)
Example: if block, for loop block, etc.
👉 Outside of any function or block
👉 Variables declared in global
scope are accessible everywhere
👉 Variables are accessible only
inside function, NOT outside
👉 Also called local scope
👉 Variables are accessible only
inside block (block scoped)
⚠ HOWEVER, this only applies to
let and const variables!
👉 Functions are also block scoped
(only in strict mode)
THE SCOPE CHAIN
Global scope
myName = “Jonas”
first() scope
age = 30
myName = “Jonas”
if block scope
decade = 3
age = 30
myName = “Jonas”
second() scope
job = “teacher”
age = 30
myName = “Jonas”
millennial = true
millennial = true
SCOPE CHAIN
Scope has access
to variables from
all outer scopes
(Considering only
variable declarations)
millennial = true
Variables not in
current scope
VARIABLE
LOOKUP
IN
SCOPE
CHAIN
let and const are block-scoped
var is function-scoped
Global variable
SCOPE CHAIN VS. CALL STACK
CALL STACK
Global EC
a = “Jonas”
first = <function>
third = <function>
Variable
environment (VE)
first() EC
b = “Hello!”
second = <function>
second() EC
c = “Hi!”
third() EC
d = “Hey!”
first() scope
b = “Hello!”
second = <function>
third() scope
d = “Hey!”
Global scope
a = “Jonas”
first = <function>
third = <function>
a = “Jonas”
first = <function>
third = <function>
a = “Jonas”
first = <function>
third = <function>
second() scope
c = “Hi!”
a = “Jonas”
first = <function>
third = <function>
b = “Hello!”
second = <function>
c and b can NOT be found
in third() scope! Order in which
functions were called
SCOPE CHAIN
Order in which functions
are written in the code
☝ Has nothing to do
with order in which
functions were called!
SUMMARY 🥳
👉 Scoping asks the question “Where do variables live?” or “Where can we access a certain variable, and where not?”;
👉 There are 3 types of scope in JavaScript: the global scope, scopes defined by functions, and scopes defined by blocks;
👉 Only let and const variables are block-scoped. Variables declared with var end up in the closest function scope;
👉 In JavaScript, we have lexical scoping, so the rules of where we can access variables are based on exactly where in the
code functions and blocks are written;
👉 Every scope always has access to all the variables from all its outer scopes. This is the scope chain!
👉 When a variable is not in the current scope, the engine looks up in the scope chain until it finds the variable it’s looking
for. This is called variable lookup;
👉 The scope chain is a one-way street: a scope will never, ever have access to the variables of an inner scope;
👉 The scope chain in a certain scope is equal to adding together all the variable environments of the all parent scopes;
👉 The scope chain has nothing to do with the order in which functions were called. It does not affect the scope chain at all!
SECTION
LECTURE
HOW JAVASCRIPT WORKS BEHIND THE
SCENES
VARIABLE ENVIRONMENT: HOISTING
AND THE TDZ
HOISTING IN JAVASCRIPT
👉 Variable environment
👉 Scope chain
👉 this keyword
EXECUTION CONTEXT
✅
👉 Hoisting: Makes some types of variables accessible/usable in the code before they are
actually declared. “Variables lifted to the top of their scope”.
Before execution, code is scanned for variable declarations, and for each variable, a new
property is created in the variable environment object.
BEHIND THE SCENES
HOISTED?
👇
INITIAL VALUE
👇
SCOPE
👇
function declarations
var variables
let and const variables
function expressions and arrows 🤷 Depends if using var or let/const
✅ YES Actual function Block
In strict mode.
Otherwise: function!
✅ YES undefined Function
🚫 NO <uninitialized>, TDZ Block
Temporal Dead Zone
Technically, yes. But
not in practice
TEMPORAL DEAD ZONE, LET AND CONST
TEMPORAL DEAD ZONE FOR job VARIABLE
ReferenceError: Cannot access 'job' before initialization
ReferenceError: x is not defined
👉 Different kinds of error messages:
WHY HOISTING? WHY TDZ?
👉 Makes it easier to avoid and catch errors: accessing variables
before declaration is bad practice and should be avoided;
👉 Makes const variables actually work
👉 Using functions before actual declaration;
👉 var hoisting is just a byproduct.
SECTION
LECTURE
HOW JAVASCRIPT WORKS BEHIND THE
SCENES
THE THIS KEYWORD
👉 Method example:
👉 Variable environment
👉 Scope chain
👉 this keyword
EXECUTION CONTEXT
✅
✅
HOW THE THIS KEYWORD WORKS
☝ this does NOT point to the function itself, and also NOT the its variable environment!
👉 this keyword/variable: Special variable that is created for every execution context (every function).
Takes the value of (points to) the “owner” of the function in which the this keyword is used.
☝ this is NOT static. It depends on how the function is called, and its value is only assigned when the
function is actually called.
Method 👉 this = <Object that is calling the method>
Simple function call 👉 this = undefined
Arrow functions 👉 this = <this of surrounding function (lexical this)>
Event listener 👉 this = <DOM element that the handler is attached to>
new, call, apply, bind 👉 <Later in the course... ⏳>
In strict mode! Otherwise:
window (in the browser)
Don’t get
own this
jonas
calcAge
is method
1989
Way better than using
jonas.year!
GOT QUESTIONS? FEEDBACK?
Just POST IT IN THE Q&A OF THIS
VIDEO, AND YOU WILL GET HELP
THERE!
SECTION
LECTURE
HOW JAVASCRIPT WORKS BEHIND THE
SCENES
PRIMITIVES VS. OBJECTS (PRIMITIVE
VS. REFERENCE TYPES)
REVIEW: PRIMITIVES, OBJECTS AND THE JAVASCRIPT ENGINE
ENGINE
CALL STACK HEAP
PRIMITIVES
👉 Number
👉 String
👉 Boolean
👉 Undefined
👉 Null
👉 Symbol
👉 BigInt
OBJECTS
👉 Object literal
👉 Arrays
👉 Functions
👉 Many more…
STORED IN
STORED IN
PRIMITIVE TYPES
REFERENCE TYPES
PRIMITIVE VS. REFERENCE VALUES
CALL STACK HEAP
👉 Primitive values example:
👉 Reference values example:
0001
Address Address Value
D30F
{
name: ‘Jonas’;
age: 30;
}
30
Value
0002 31
0003
oldAge
me
friend
No problem, because
we’re NOT changing the
value at address 0003!
D30F
Reference to memory
address in Heap
age
Identifier
27
31
“HOW JAVASCRIPT WORKS BEHIND THE SCENES” TOPICS FOR LATER... ⏳
1 Prototypal Inheritance 👉 Object Oriented Programming (OOP) With JavaScript
2 Event Loop 👉 Asynchronous JavaScript: Promises, Async/Await and AJAX
3 How the DOM Really Works 👉 Advanced DOM and Events
DATA STRUCTURES,
MODERN OPERATORS
AND STRINGS
SECTION
LECTURE
DATA STRUCTURES, MODERN
OPERATORS AND STRINGS
SUMMARY: WHICH DATA STRUCTURE
TO USE?
👉 JSON data format example
1
2
3
SOURCES OF DATA
DATA STRUCTURES OVERVIEW
Array
“Object”
“Object”
From the program itself: Data written directly in source code (e.g. status messages)
From the UI: Data input from the user or data written in DOM (e.g tasks in todo app)
From external sources: Data fetched for example from web API (e.g. recipe objects)
Data structure
Collection of data
Arrays or Sets
SIMPLE LIST?
Objects or Maps
KEY/VALUE PAIRS?
Application
Programming
Interface
Keys allow us to
describe values
👉 Stacks
👉 Queues
👉 Linked lists
👉 Trees
👉 Hash tables
NON-BUILT IN:
👉 WeakMap
👉 WeakSet
OTHER BUILT-IN:
ARRAYS SETS
VS.
ARRAYS VS. SETS AND OBJECTS VS. MAPS
OBJECTS MAPS
VS.
👉 Use when you need ordered
list of values (might contain
duplicates)
👉 Use when you need to
manipulate data
👉 Use when you need to work
with unique values
👉 Use when high-performance
is really important
👉 Use to remove duplicates
from arrays
👉 Better performance
👉 Keys can have any data type
👉 Easy to iterate
👉 Easy to compute size
👉 More “traditional” key/value
store (“abused” objects)
👉 Easier to write and access
values with . and []
👉 Use when you simply need
to map key to values
👉 Use when you need keys
that are not strings
👉 Use when you need to
include functions (methods)
👉 Use when working with
JSON (can convert to map)
A CLOSER LOOK AT
FUNCTIONS
SECTION
LECTURE
A CLOSER LOOK AT FUNCTIONS
FIRST-CLASS AND HIGHER-ORDER
FUNCTIONS
FIRST-CLASS VS. HIGHER-ORDER FUNCTIONS
👉 JavaScript treats functions as first-class citizens
👉 This means that functions are simply values
👉 Functions are just another “type” of object
FIRST-CLASS FUNCTIONS
👉 Return functions FROM functions
👉 A function that receives another function as an
argument, that returns a new function, or both
👉 This is only possible because of
fi
rst-class functions
HIGHER-ORDER FUNCTIONS
👉 Store functions in variables or properties:
👉 Pass functions as arguments to OTHER functions:
👉 Call methods on functions:
👉 Function that returns new function
2
👉 Function that receives another function
1
Callback
function
Higher-order
function
Higher-order
function
Returned
function
✅ 📞 💬
SECTION
LECTURE
A CLOSER LOOK AT FUNCTIONS
CLOSURES
“CREATING” A CLOSURE
CALL STACK
Global EC
secureBooking = <f>
booker = <f>
secureBooking() scope
passengerCount = 0
secureBooking = <f>
Global scope
secureBooking = <f>
Order in which
functions were called
SCOPE CHAIN
Order in which functions
are written in the code
booker = <f>
booker = <f>
secureBooking() EC
passengerCount = 0
Variable
Environment
UNDERSTANDING CLOSURES
CALL STACK
Global EC
secureBooking = <f>
booker = <f>
secureBooking() scope
passengerCount = 0
secureBooking = <f>
Global scope
secureBooking = <f>
SCOPE CHAIN
booker() EC
<empty>
Variable Environment of
Execution Context in which
booker was created
booker() scope
secureBooking = <f>
booker = <f>
<empty>
This is the function
booker = <f>
booker = <f>
How to access
passengerCount?
passengerCount = 0
secureBooking() EC
passengerCount = 0
UNDERSTANDING CLOSURES
CALL STACK
Global EC
secureBooking = <f>
booker = <f>
SCOPE CHAIN
booker() scope
secureBooking = <f>
booker = <f>
<empty>
passengerCount = 0
CLOSURE
👉 A function has access to the variable environment (VE) of the execution context in which it was created
👉 Closure: VE attached to the function, exactly as it was at the time and place the function was created Global scope
secureBooking = <f>
booker = <f>
This is the function
How to access
passengerCount?
1
2
(Priority over
scope chain)
secureBooking() scope
passengerCount = 0
secureBooking = <f>
booker = <f>
booker() EC
<empty>
👉 A closure is the closed-over variable environment of the execution context in which a function was created, even after that
execution context is gone;
👉 A closure gives a function access to all the variables of its parent function, even after that parent function has returned. The
function keeps a reference to its outer scope, which preserves the scope chain throughout time.
👉 A closure makes sure that a function doesn’t loose connection to variables that existed at the function’s birth place;
👉 A closure is like a backpack that a function carries around wherever it goes. This backpack has all the variables that were
present in the environment where the function was created.
CLOSURES SUMMARY 🥳
☝ We do NOT have to manually create closures, this is a JavaScript feature that happens automatically. We can’t even
access closed-over variables explicitly. A closure is NOT a tangible JavaScript object.
Function Connection Parent scope Variables
Function Closure Variables
Less formal
Less formal
Less formal
WORKING WITH
ARRAYS
SECTION
LECTURE
WORKING WITH ARRAYS
DATA TRANSFORMATIONS: MAP, FILTER,
REDUCE
MAP FILTER REDUCE
DATA TRANSFORMATIONS WITH MAP, FILTER AND REDUCE
👉 map returns a new array containing
the results of applying an operation
on all original array elements
3 1 4 3 2
6 2 8 6 4
current * 2
Original array
👉 filter returns a new array
containing the array elements that
passed a speci
fi
ed test condition
3 1 4 3 2
3 4 3
current > 2
Filtered array
👉 reduce boils (“reduces”) all array
elements down to one single value
(e.g. adding all elements together)
3 1 4 3 2
3
acc + current
Example
1 2
4
8
11
13
Accumulator
Reduced value
SECTION
LECTURE
WORKING WITH ARRAYS
SUMMARY: WHICH ARRAY METHOD TO
USE?
WHICH ARRAY METHOD TO USE? 🤔
.find
👉 Based on test condition:
.indexOf
.findIndex
👉 Based on test condition:
👉 Based on value:
To mutate original array A new array Know if array includes
To just loop array
An array index To transform to value
An array element A new string
.some
.includes
.every
👉 Based on value:
👉 Based on test condition:
.join
👉 Based on separator string:
.forEach
👉 Based on callback:
(Does not create a new array,
just loops over it)
.reduce
👉 Based on accumulator:
(Boil down array to single
value of any type: number,
string, boolean, or even new
array or object)
“I WANT...:”
.splice
.reverse
.sort
.push
.pop
.shift
.unshift
👉 Add to original:
👉 Remove from original:
(end)
(start)
(end)
(start)
(any)
👉 Others:
.fill
.slice
.concat
.map
.filter
.flat
.flatMap
👉 Computed from original:
👉 Filtered using condition:
(loop)
👉 Portion of original:
👉 Adding original to other:
👉 Flattening the original:
ADVANCED DOM AND
EVENTS
SECTION
LECTURE
ADVANCED DOM AND EVENTS
HOW THE DOM REALLY WORKS
REVIEW: WHAT IS THE DOM?
BROWSER
INTERFACE
DOM
👉 Allows us to make JavaScript interact with the browser;
👉 We can write JavaScript to create, modify and delete HTML elements;
set styles, classes and attributes; and listen and respond to events;
👉 DOM tree is generated from an HTML document, which we can then
interact with;
👉 DOM is a very complex API that contains lots of methods and
properties to interact with the DOM tree
Application Programming Interface
.querySelector() / .addEventListener() / .createElement() /
.innerHTML / .textContent / .children / etc ...
“Types” of
DOM objects
(next slide)
DOM tree
Nodes
HOW THE DOM API IS ORGANIZED BEHIND THE SCENES
Node
(THIS IS NOT A DOM TREE)
EventTarget
Window
HTMLElement
HTMLButtonElement HTMLDivElement
...
Document
.addEventListener()
.removeEventListener()
Global object, lots
of methods and
properties, many
unrelated to DOM
.textContent
.childNodes
.parentNode
.cloneNode()
.innerHTML
.classList
.children
.parentElement
.append()
.remove()
.insertAdjacentHTML()
.querySelector()
.closest()
.matches()
.scrollIntoView()
.setAttribute()
INHERITANCE OF
METHODS AND
PROPERTIES
Example:
Any HTMLElement will
have access to
.addEventListener(),
.cloneNode()
or .closest() methods.
Text Comment
Element
(One different type of
HTMLElement per
HTML element...)
Represented by
JavaScript object
<p>Paragraph<p>
<p>Paragraph<p> <!--Comment--> .querySelector()
.createElement()
.getElementById()
SECTION
LECTURE
ADVANCED DOM AND EVENTS
EVENT PROPAGATION: BUBBLING AND
CAPTURING
1
CAPTURING
PHASE
3
BUBBLING
PHASE
2 TARGET PHASE
Click event
BUBBLING AND CAPTURING
(THIS DOES NOT HAPPEN
ON ALL EVENTS)
SECTION
LECTURE
ADVANCED DOM AND EVENTS
EFFICIENT SCRIPT LOADING: DEFER
AND ASYNC
DEFER
ASYNC
REGULAR
DEFER AND ASYNC SCRIPT LOADING
HEAD BODY END
Execute
Parsing HTML
Fetch script
Waiting... Finish parsing HTML
Time DOMContentLoaded
Parsing HTML Execute
Fetch script
DOMContentLoaded
Execute
Parsing HTML
Fetch script
Waiting Finish parsing HTML
DOMContentLoaded
Execute
Parsing HTML
Fetch script DOMContentLoaded
👉 Makes no sense 🤷
👉 Makes no sense 🤷
REGULAR VS. ASYNC VS. DEFER
👉 Scripts are fetched asynchronously and
executed immediately
👉 Usually the DOMContentLoaded event
waits for all scripts to execute, except for
async scripts. So, DOMContentLoaded
does not wait for an async script
👉 Scripts not guaranteed to execute in order
👉 Use for 3rd-party scripts where order
doesn’t matter (e.g. Google Analytics)
Run
Parse HTML
Fetch
Wait Parse HTML
DOMContentLoaded
Run
Parse HTML
Fetch DOMContentLoaded
Run
Parse HTML Fetch
DOMContentLoaded
Run
Parse HTML
Fetch
DOMContentLoaded
ASYNC IN HEAD DEFER IN HEAD
END OF BODY
Run
Parse HTML
Fetch
DOMContentLoaded
👉 Scripts are fetched and executed after the
HTML is completely parsed
👉 Use if you need to support old browsers
👉 Scripts are fetched asynchronously and
executed after the HTML is completely
parsed
👉 DOMContentLoaded event fires after
defer script is executed
👉 Scripts are executed in order
👉 This is overall the best solution! Use for
your own scripts, and when order matters
(e.g. including a library)
You can, of course, use different
strategies for different scripts. Usually a
complete web applications includes
more than just one script
OBJECT ORIENTED
PROGRAMMING (OOP)
WITH JAVASCRIPT
SECTION
LECTURE
OBJECT ORIENTED PROGRAMMING
(OOP) WITH JAVASCRIPT
WHAT IS OBJECT-ORIENTED
PROGRAMMING?
WHAT IS OBJECT-ORIENTED PROGRAMMING? (OOP)
OOP
Style of code, “how” we
write and organize code
👉 Object-oriented programming (OOP) is a programming paradigm based on the
concept of objects;
👉 We use objects to model (describe) real-world or abstract features;
👉 Objects may contain data (properties) and code (methods). By using objects, we
pack data and the corresponding behavior into one block;
👉 In OOP, objects are self-contained pieces/blocks of code;
👉 Objects are building blocks of applications, and interact with one another;
👉 Interactions happen through a public interface (API): methods that the code
outside of the object can access and use to communicate with the object;
👉 OOP was developed with the goal of organizing code, to make it more flexible
and easier to maintain (avoid “spaghetti code”).
E.g. user or todo list item
E.g. HTML component or data structure
Data
Behaviour
Like a blueprint from
which we can create
new objects
CLASSES AND INSTANCES (TRADITIONAL OOP)
CLASS
Instance
Instance
Instance
Just a representation,
NOT actual JavaScript
syntax!
JavaScript does NOT
support real classes
like represented here
New object created from the class. Like a
real house created from an abstract blueprint
☝ Conceptual overview: it works
a bit differently in JavaScript.
Still important to understand!
THE 4 FUNDAMENTAL OOP PRINCIPLES
Abstraction
Polymorphism
Inheritance
Encapsulation
The 4 fundamental
principles of Object-
Oriented Programming
🤔 “How do we actually design classes? How
do we model real-world data into classes?”
PRINCIPLE 1: ABSTRACTION
Polymorphism
Inheritance
Abstraction
Encapsulation
👉 Abstraction: Ignoring or hiding details that don’t matter, allowing us to
get an overview perspective of the thing we’re implementing, instead of
messing with details that don’t really matter to our implementation.
Real phone Abstracted phone
Do we really need all these low-level details?
Details have been
abstracted away
PRINCIPLE 2: ENCAPSULATION
Polymorphism
Inheritance
Again, NOT actually JavaScript
syntax (the private keyword
doesn’t exist)
Abstraction
Encapsulation
👉 Encapsulation: Keeping properties and methods private inside the class,
so they are not accessible from outside the class. Some methods can
be exposed as a public interface (API).
NOT accessible from
outside the class!
STILL accessible from
within the class!
NOT accessible from
outside the class!
STILL accessible from
within the class!
👉 Prevents external code from
accidentally manipulating
internal properties/state
👉 Allows to change internal
implementation without the
risk of breaking external code
WHY?
PRINCIPLE 3: INHERITANCE
Polymorphism
Inheritance
Abstraction
Encapsulation
👉 Inheritance: Making all properties and methods of a certain class available
to a child class, forming a hierarchical relationship between classes. This
allows us to reuse common logic and to model real-world relationships.
PARENT CLASS
CHILD CLASS
INHERITANCE
Inherited
OWN methods
and properties
Inherited
CHILD CLASS EXTENDS PARENT CLASS
PRINCIPLE 4: POLYMORPHISM
Inheritance
Polymorphism
Abstraction
Encapsulation
👉 Polymorphism: A child class can overwrite a method it inherited from a
parent class [it’s more complex that that, but enough for our purposes].
PARENT CLASS
CHILD CLASS CHILD CLASS
INHERITANCE INHERITANCE
Own login method,
overwriting login method
inherited from User
SECTION
LECTURE
OBJECT ORIENTED PROGRAMMING
(OOP) WITH JAVASCRIPT
OOP IN JAVASCRIPT
👉 Example: Array
“CLASSICAL OOP”: CLASSES
OOP IN JAVASCRIPT: PROTOTYPES
Array.prototype is the
prototype of all array objects
we create in JavaScript
Therefore, all arrays have
access to the map method!
Class
Instance
OOP IN JS: PROTOTYPES
👉 Objects (instances) are
instantiated from a class, which
functions like a blueprint;
👉 Behavior (methods) is copied from
class to all instances.
Prototype
Object
INSTANTIATION PROTOTYPAL INHERITANCE/
DELEGATION
👉 Objects are linked to a prototype object;
👉 Prototypal inheritance: The prototype
contains methods (behavior) that are
accessible to all objects linked to that
prototype;
👉 Behavior is delegated to the linked
prototype object.
Contains
methods
Can access
methods
3 WAYS OF IMPLEMENTING PROTOTYPAL INHERITANCE IN JAVASCRIPT
🤔 “How do we actually create prototypes? And how do we link objects to
prototypes? How can we create new objects, without having classes?”
3 Object.create()
👉 The easiest and most straightforward way of linking an object to a prototype object.
2 ES6 Classes
👉 Modern alternative to constructor function syntax;
👉 “Syntactic sugar”: behind the scenes, ES6 classes work exactly like constructor functions;
👉 ES6 classes do NOT behave like classes in “classical OOP” (last lecture).
1 Constructor functions
👉 Technique to create objects from a function;
👉 This is how built-in objects like Arrays, Maps or Sets are actually implemented.
👉 Abstraction
👉 Encapsulation
👉 Inheritance
👉 Polymorphism
☝ The 4 pillars of OOP
are still valid!
SECTION
LECTURE
OBJECT ORIENTED PROGRAMMING
(OOP) WITH JAVASCRIPT
PROTOTYPAL INHERITANCE AND THE
PROTOTYPE CHAIN
🆕 The new operator:
HOW PROTOTYPAL INHERITANCE / DELEGATION WORKS
1 An empty object is created
2 this keyword in
constructor function call
is set to the new object
3 The new object is linked
(__proto__ property) to
the constructor function’s
prototype property
4 The new object is
returned from the
constructor function call
Object
[jonas]
PROTOTYPAL
INHERITANCE/
DELEGATION
Constructor function
[Person()]
Prototype
[Person.prototype]
calcAge: function
name: ‘Jonas’
birthYear: 1990
__proto__:
Person.prototype
.__proto__
.prototype
.constructor
☝ This is how it works with function
constructors and ES6 classes
PROTOTYPE
CHAIN
Always points to an
object’s prototype
Can’t find calcAge here!
NOT of Person, but objects created by Person
Prototype
[Object.prototype]
.__proto__
THE PROTOTYPE CHAIN
.__proto__
__proto__: null
Prototype
[Person.prototype]
__proto__:
Object.prototype
Object
[jonas]
__proto__:
Person.prototype
null
This is an OBJECT
itself! Remember, every
object in JavaScript
has a prototype!
Constructor function
[Person()]
Constructor function
[Object()]
PROTOTYPE
CHAIN
Series of links
between objects,
linked through
prototypes
(Similar to the
scope chain)
Built-in constructor function
for objects. This is used when
we write an object literal:
{…} === new Object(…)
Can’t find hasOwnProperty here!
Can’t find
hasOwnProperty
here!
Here it is!
SECTION
LECTURE
OBJECT ORIENTED PROGRAMMING
(OOP) WITH JAVASCRIPT
OBJECT.CREATE
Object
[steven]
name: ‘Steven’
birthYear: 2002
__proto__:
PersonProto
OBJECT.CREATE
CONSTRUCTOR FUNCTIONS
HOW OBJECT.CREATE WORKS
AUTOMATIC
Prototype
[PersonProto]
calcAge: function
.__proto__
SECTION
LECTURE
OBJECT ORIENTED PROGRAMMING
(OOP) WITH JAVASCRIPT
INHERITANCE BETWEEN "CLASSES":
CONSTRUCTOR FUNCTIONS
INHERITANCE BETWEEN “CLASSES”
Prototype
Object
More specific type
of person, ideal as
child class
Constructor
Function
Prototype
Constructor
Function
“CLASS” 1
STUDENT
“CLASS” 2
PERSON
1 Constructor functions
2 ES6 Classes
3 Object.create()
INHERITANCE BETWEEN “CLASSES”
☝ Using class terminology here to
make it easier to understand.
Child
Parent
Prototype
[Person.prototype]
.__proto__
INHERITANCE BETWEEN “CLASSES”
.__proto__
Prototype
[Student.prototype]
Object
[mike]
__proto__:
Student.prototype
Constructor function
[Student()]
Constructor function
[Person()]
__proto__:
Person.prototype
PROTOTYPE
CHAIN
Create connection
manually using
Object.create()
INHERITANCE BETWEEN “CLASSES”
Prototype
[Person.prototype]
Object
[mike]
__proto__:
Student.prototype
Constructor function
[Student()]
Constructor function
[Person()]
👎 BAD
👍 GOOD
Prototype
[Person.prototype]
.__proto__
INHERITANCE BETWEEN “CLASSES”
.__proto__
__proto__:
Object.prototype
Prototype
[Student.prototype]
__proto__:
Person.prototype
Object
[mike]
__proto__:
Student.prototype
Constructor function
[Student()]
Constructor function
[Person()]
PROTOTYPE
CHAIN
Can’t find calcAge here!
Can’t find
calcAge here!
null
Prototype
[Object.prototype]
Here it is!
SECTION
LECTURE
OBJECT ORIENTED PROGRAMMING
(OOP) WITH JAVASCRIPT
INHERITANCE BETWEEN "CLASSES":
OBJECT.CREATE
INHERITANCE BETWEEN “CLASSES”: OBJECT.CREATE
Prototype
[PersonProto]
calcAge: function
PROTOTYPE
CHAIN
.__proto__
Prototype
[StudentProto]
__proto__:
PersonProto
.__proto__
Object
[jay]
__proto__:
StudentProto
Student
inherits from
Person
SECTION
LECTURE
OBJECT ORIENTED PROGRAMMING
(OOP) WITH JAVASCRIPT
ES6 CLASSES SUMMARY
Public field (similar to property, available on created object)
Private fields (not accessible outside of class)
Static public field (available only on class)
Call to parent (super) class (necessary with
extend). Needs to happen before accessing this
Static method (available only on class. Can not access
instance properties nor methods, only static ones)
Setter method (use _ to set property with
same name as method, and also add getter)
Getter method
Public method
Private method (⚠ Might not yet work in your
browser. “Fake” alternative: _ instead of #)
Creating new object with new operator
Referencing private field and method
Constructor method,
called by new operator.
Mandatory in regular
class, might be omitted
in a child class
Child class
Parent class
Instance property (available on created object)
Redefining private field
Inheritance between
classes, automatically
sets prototype
👉 Classes are just
“syntactic sugar” over
constructor functions
👉 Classes are not hoisted
👉 Classes are first-class
citizens
👉 Class body is always
executed in strict mode
MAPTY APP: OOP,
GEOLOCATION,
EXTERNAL LIBRARIES,
AND MORE!
SECTION
LECTURE
MAPTY APP: OOP, GEOLOCATION,
EXTERNAL LIBRARIES, AND MORE!
HOW TO PLAN A WEB PROJECT
PROJECT PLANNING
1.
USER STORIES
PLANNING STEP
2.
FEATURES
3.
FLOWCHART
4.
ARCHITECTURE
DEVELOPMENT
STEP
Description of the application’s
functionality from the user’s
perspective. All user stories put
together describe the entire application.
Implementation of
our plan using code
WHAT we will build HOW we will build it
1. USER STORIES
1
As a user, I want to log my running workouts with location, distance, time, pace and
steps/minute, so I can keep a log of all my running
As a user, I want to log my cycling workouts with location, distance, time, speed and
elevation gain, so I can keep a log of all my cycling
As a user, I want to see all my workouts at a glance, so I can easily track my progress
over time
As a user, I want to also see my workouts on a map, so I can easily check where I
work out the most
As a user, I want to see all my workouts when I leave the app and come back later, so
that I can keep using there app over time
👉 User story: Description of the application’s functionality from the user’s perspective.
👉 Common format: As a [type of user], I want [an action] so that [a bene
fi
t]
Who?
Example: user, admin, etc.
What? Why?
2
3
4
5
2. FEATURES
1
Log my running workouts with location,
distance, time, pace and steps/minute
Log my cycling workouts with location,
distance, time, speed and elevation gain
See all my workouts at a glance
See my workouts on a map
See all my workouts when I leave the
app and come back later
2
3
4
5
👉 Map where user clicks to add new workout (best way to
get location coordinates)
👉 Geolocation to display map at current location (more user
friendly)
👉 Form to input distance, time, pace, steps/minute
👉 Form to input distance, time, speed, elevation gain
👉 Display all workouts in a list
👉 Display all workouts on the map
👉 Store workout data in the browser using local storage API
👉 On page load, read the saved data from local storage and
display
USER STORIES FEATURES
3. FLOWCHART
1. Geolocation to display
map at current location
2. Map where user clicks to
add new workout
3. Form to input distance,
time, pace, steps/minute
4. Form to input distance,
time, speed, elevation gain
5. Display workouts in a list
6. Display workouts on the
map
7. Store workout data in the
browser
8. On page load, read the
saved data and display
9. Move map to workout
location on click
FEATURES
Added later
1 2 3 4
5
6
7
8
9
☝ In the real-world, you don’t have to come with the final flowchart right in the
planning phase. It’s normal that it changes throughout implementation!
4. ARCHITECTURE
FOR NOW, LET’S JUST
START CODING 😍
SECTION
LECTURE
MAPTY APP: OOP, GEOLOCATION,
EXTERNAL LIBRARIES, AND MORE!
FINAL CONSIDERATIONS
10 ADDITIONAL FEATURE IDEAS: CHALLENGES 🤓
👉 Ability to edit a workout;
👉 Ability to delete a workout;
👉 Ability to delete all workouts;
👉 Ability to sort workouts by a certain field (e.g. distance);
👉 Re-build Running and Cycling objects coming from Local Storage;
👉 More realistic error and confirmation messages;
👉 Ability to position the map to show all workouts [very hard];
👉 Ability to draw lines and shapes instead of just points [very hard];
👉 Geocode location from coordinates (“Run in Faro, Portugal”) [only after
asynchronous JavaScript section];
👉 Display weather data for workout time and place [only after asynchronous
JavaScript section].
ASYNCHRONOUS
JAVASCRIPT:
PROMISES, ASYNC/
AWAIT AND AJAX
SECTION
LECTURE
ASYNCHRONOUS JAVASCRIPT:
PROMISES, ASYNC/AWAIT AND AJAX
ASYNCHRONOUS JAVASCRIPT, AJAX
AND APIS
SYNCHRONOUS CODE
SYNCHRONOUS
THREAD OF
EXECUTION
👉 Most code is synchronous;
👉 Synchronous code is executed line by line;
👉 Each line of code waits for previous line to finish;
👎 Long-running operations block code execution.
BLOCKING
Part of execution
context that actually
executes the code in
computer’s CPU
ASYNCHRONOUS CODE
ASYNCHRONOUS
THREAD OF
EXECUTION
CALLBACK WILL
RUN AFTER TIMER
👉 Asynchronous code is executed after a task that runs in the “background” finishes;
👍 Asynchronous code is non-blocking;
👉 Execution doesn’t wait for an asynchronous task to finish its work;
👉 Callback functions alone do NOT make code asynchronous!
“BACKGROUND”
(More on this in the
lecture on Event Loop)
👉 Example: Timer with callback
Callback does NOT automatically
make code asynchronous!
Timer
running
Executed after
all other code
Asynchronous
Coordinating behavior of a
program over a period of time
ASYNCHRONOUS CODE
ASYNCHRONOUS
THREAD OF
EXECUTION
CALLBACK WILL RUN
AFTER IMAGE LOADS
👉 Asynchronous code is executed after a task that runs in the “background” finishes;
👍 Asynchronous code is non-blocking;
👉 Execution doesn’t wait for an asynchronous task to finish its work;
👉 Callback functions alone do NOT make code asynchronous!
“BACKGROUND”
(More on this in the
lecture on Event Loop)
👉 Example: Asynchronous image loading with event and callback
Image
loading
Asynchronous
👉 Other examples: Geolocation API or AJAX calls
addEventListener does
NOT automatically make
code asynchronous!
Coordinating behavior of a
program over a period of time
WHAT ARE AJAX CALLS?
CLIENT
(e.g. browser)
👩💻
WEB
SERVER
🌐
REQUEST
RESPONSE
Asynchronous JavaScript And XML: Allows us to communicate with
remote web servers in an asynchronous way. With AJAX calls, we can
request data from web servers dynamically.
Asking for some data 🇵🇹 🇫🇮 🇬🇭
Sending data back 🇵🇹 🇫🇮 🇬🇭
(GET / POST / etc.)
AJAX
Usually a
web API
WHAT IS AN API?
👉 Application Programming Interface: Piece of software
that can be used by another piece of software, in order to
allow applications to talk to each other;
👉 There are be many types of APIs in web development:
👉 “Online” API: Application running on a server, that receives
requests for data, and sends data back as response;
👉 We can build our own web APIs (requires back-end
development, e.g. with node.js) or use 3rd-party APIs.
DOM API Geolocation API Own Class API “Online” API
API
👉 Weather data
👉 Data about countries
👉 Flights data
👉 Currency conversion data
👉 APIs for sending email or SMS
👉 Google Maps
👉 Millions of possibilities...
There is an API for
everything
AJAX
XML data
format
✈ 🌍
JSON data
format
Most popular
API data format
Just “API”
SECTION
LECTURE
ASYNCHRONOUS JAVASCRIPT:
PROMISES, ASYNC/AWAIT AND AJAX
HOW THE WEB WORKS: REQUESTS
AND RESPONSES
WHAT HAPPENS WHEN WE ACCESS A WEB SERVER
CLIENT
(e.g. browser)
👩💻
WEB
SERVER
🌐
REQUEST
RESPONSE
👉 Request-response model or Client-server architecture
WHAT HAPPENS WHEN WE ACCESS A WEB SERVER
GET /rest/v2/alpha/PT HTTP/1.1
Host: www.google.com
User-Agent: Mozilla/5.0
Accept-Language: en-US
<BODY>
HTTP REQUEST
HTTP RESPONSE
TCP/IP socket connection
1
DNS
DNS
LOOKUP
3
4
WEB
SERVER
🌐
Start line: HTTP method + request target + HTTP version
HTTP request headers (many different possibilities)
2
Request body (only when sending data to server, e.g. POST)
HTTP/1.1 200 OK
Date: Fri, 18 Jan 2021
Content-Type: text/html
Transfer-Encoding: chunked
<BODY>
Start line: HTTP version + status code + status message
HTTP response headers (many different possibilities)
Response body (most responses)
CLIENT
(e.g. browser)
👩💻
h
tt
ps:/
/restcountries.eu/rest/v2/alpha/
h
tt
ps:/
/104.27.142.889:443
Protocol
(HTTP or HTTPS)
Domain name Resource
Protocol
(HTTP or HTTPS)
SECTION
LECTURE
ASYNCHRONOUS JAVASCRIPT:
PROMISES, ASYNC/AWAIT AND AJAX
PROMISES AND THE FETCH API
WHAT ARE PROMISES?
👉 Promise: An object that is used as a placeholder for the future
result of an asynchronous operation.
👉 Promise: A container for an asynchronously delivered value.
👉 Promise: A container for a future value.
Less formal
Less formal
PROMISE
👉 We no longer need to rely on events and callbacks passed into
asynchronous functions to handle asynchronous results;
👉 Instead of nesting callbacks, we can chain promises for a
sequence of asynchronous operations: escaping callback hell 🎉
Example: Response
from AJAX call
🎟
LOTTERY
TICKET
Promise that I will
receive money if I guess
correct outcome
🤞 I buy lottery ticket (promise)
right now
🔮 Lottery draw happens
asynchronously
💰 If correct outcome, I receive
money, because it was promised
THE PROMISE LIFECYCLE
🔮
🎟
LOTTERY
TICKET
PENDING
Before the future
value is available
SETTLED
Asynchronous task
has
fi
nished
FULFILLED
Success! The value
is now available
REJECTED
An error
happened
💩
💰
ASYNC TASK
👉 We are able handle these different states in our code!
CONSUME
PROMISE
BUILD
PROMISE
When we already have a
promise. E.g. promise
returned from Fetch API
E.g. Fetch API returns promise
SECTION
LECTURE
ASYNCHRONOUS JAVASCRIPT:
PROMISES, ASYNC/AWAIT AND AJAX
ASYNCHRONOUS BEHIND THE SCENES:
THE EVENT LOOP
REVIEW: JAVASCRIPT RUNTIME
“Container” which includes all the pieces
necessary to execute JavaScript code
“Heart” of
the runtime
Where object are
stored in memory
Where code is
actually executed
APIs provided
to the engine
Only ONE thread of
execution. No multitasking!
Ready-to-be-executed
callback functions
(coming from events)
Sends callbacks
from queue to
call stack
👉 Concurrency model: How JavaScript handles
multiple tasks happening at the same time.
MICROTASKS
QUEUE
HOW ASYNCHRONOUS JAVASCRIPT WORKS BEHIND THE SCENES
CALL STACK
fetch()
Global Execution
context
CALLBACK
QUEUE
EVENT LOOP
WEB APIs
setTimeout()
DOM()
...
Another
callback
Some
callback
Like callback queue, but for
callbacks related to promises.
Has priority over callback queue!
Execution context
addEventListener()
Execution context
add()
Execution context
fetch()
Execution context
then()
Execution context
el.src callback
Execution context
fetch callback
Execution context
log()
Execution context
querySelector()
Fetching data
Loading image
🤔 How can asynchronous code be
executed in a non-blocking way,
if there is only one thread of
execution in the engine?
Where asynchronous tasks run
Decides when each callback
is executed: orchestration
Loading image 👎
MODERN JAVASCRIPT
DEVELOPMENT:
MODULES AND
TOOLING
SECTION
LECTURE
MODERN JAVASCRIPT DEVELOPMENT:
MODULES AND TOOLING
AN OVERVIEW OF MODERN
JAVASCRIPT DEVELOPMENT
NODE PACKAGE
MANAGER
MODERN JAVASCRIPT DEVELOPMENT
BUNDLING
JAVASCRIPT
BUNDLE
TRANSPILING/
POLYFILLING
PRODUCTION
DEVELOPMENT
MODULE
3RD-PARTY
PACKAGE
BUILD PROCESS
Convert modern
JavaScript back to ES5
Join all modules
into one file
👉 Contains open-source packages to include 3rd-party
code in our own code (e.g React, jQuery, Leaflet, etc.)
👉 Contains development tools that help build our
applications (e.g. live-server, Parcel, Babel, etc.)
3rd party modules Development tools
or
MODULE
Both repository and software
SECTION
LECTURE
MODERN JAVASCRIPT DEVELOPMENT:
MODULES AND TOOLING
AN OVERVIEW OF MODULES IN
JAVASCRIPT
AN OVERVIEW OF MODULES
👉 Reusable piece of code that
encapsulates implementation details;
👉 Usually a standalone file, but it doesn’t
have to be.
MODULE
MODULE
IMPORT
(DEPENDENCY)
EXPORT
(PUBLIC API)
Module code
👉 Compose software: Modules are small building blocks
that we put together to build complex applications;
👉 Isolate components: Modules can be developed in
isolation without thinking about the entire codebase;
👉 Abstract code: Implement low-level code in modules and
import these abstractions into other modules;
👉 Organized code: Modules naturally lead to a more
organized codebase;
👉 Reuse code: Modules allow us to easily reuse the same
code, even across multiple projects.
WHY
MODULES?
Asynchronous
👉 File downloading
Scoped to module
👉 Top-level variables
Strict mode
👉 Default mode
<script type="module">
👉 HTML linking
undefined
👉 Top-level this
✅ YES
👉 Imports and exports
NATIVE JAVASCRIPT (ES6) MODULES
ES6 MODULE
Global
SCRIPT
“Sloppy” mode
<script>
window
🚫 NO
☝ Need to happen at top-level
Imports are hoisted!
Synchronous
ES6 MODULES
Modules stored in files, exactly
one module per file.
import and export
syntax
Execution index.js
IMPORTING MODULES
BEFORE EXECUTION
HOW ES6 MODULES ARE IMPORTED
Asynchronous
downloading math.js
Asynchronous
downloading dom.js
👉 index.js
Linking imports to
math.js exports
Linking imports to
dom.js exports
Execution math.js Execution dom.js
Parsing index.js
👉 math.js
👉 dom.js
Live connection,
NOT copies
👉 Modules are imported synchronously
👉 Possible thanks to top-level (“static”) imports,
which make imports known before execution
👉 This makes bundling and dead code
elimination possible
Live connection,
NOT copies
SECTION
LECTURE
MODERN JAVASCRIPT DEVELOPMENT:
MODULES AND TOOLING
REVIEW: WRITING CLEAN AND
MODERN JAVASCRIPT
REVIEW: MODERN AND CLEAN CODE
👉 Write code so that others can understand it
👉 Write code so that you can understand it in 1 year
👉 Avoid too “clever” and overcomplicated solutions
👉 Use descriptive variable names: what they contain
👉 Use descriptive function names: what they do
READABLE CODE
👉 Use DRY principle (refactor your code)
👉 Don’t pollute global namespace, encapsulate instead
👉 Don’t use var
👉 Use strong type checks (=== and !==)
GENERAL
👉 Generally, functions should do only one thing
👉 Don’t use more than 3 function parameters
👉 Use default parameters whenever possible
👉 Generally, return same data type as received
👉 Use arrow functions when they make code more readable
FUNCTIONS
OOP
👉 Use ES6 classes
👉 Encapsulate data and don’t mutate it from outside the class
👉 Implement method chaining
👉 Do not use arrow functions as methods (in regular objects)
REVIEW: MODERN AND CLEAN CODE
👉 Use early return (guard clauses)
👉 Use ternary (conditional) or logical operators instead of if
👉 Use multiple if instead of if/else-if
👉 Avoid for loops, use array methods instead
👉 Avoid callback-based asynchronous APIs
AVOID NESTED CODE ASYNCHRONOUS CODE
👉 Consume promises with async/await for best readability
👉 Whenever possible, run promises in parallel (Promise.all)
👉 Handle errors and promise rejections
SECTION
LECTURE
MODERN JAVASCRIPT DEVELOPMENT:
MODULES AND TOOLING
DECLARATIVE AND FUNCTIONAL
JAVASCRIPT PRINCIPLES
IMPERATIVE VS. DECLARATIVE CODE
👉 Programmer explains “HOW to do things”
👉 We explain the computer every single step it has to
follow to achieve a result
👉 Example: Step-by-step recipe of a cake
👉 Programmer tells “WHAT do do”
👉 We simply describe the way the computer should achieve
the result
👉 The HOW (step-by-step instructions) gets abstracted away
👉 Example: Description of a cake
Two fundamentally different ways
of writing code (paradigms)
DECLARATIVE
IMPERATIVE
FUNCTIONAL PROGRAMMING PRINCIPLES
👉 Use array and object destructuring
👉 Use the spread operator (...)
👉 Use the ternary (conditional) operator
👉 Use template literals
DECLARATIVE SYNTAX
FUNCTIONAL PROGRAMMING TECHNIQUES
👉 Try to avoid data mutations
👉 Use built-in methods that don’t produce side effects
👉 Do data transformations with methods such
as .map(), .filter() and .reduce()
👉 Try to avoid side effects in functions: this is of course not
always possible!
FUNCTIONAL PROGRAMMING
👉 Declarative programming paradigm
👉 Based on the idea of writing software by combining many
pure functions, avoiding side effects and mutating data
👉 Side effect: Modification (mutation) of any data outside
of the function (mutating external variables, logging to
console, writing to DOM, etc.)
👉 Pure function: Function without side effects. Does not
depend on external variables. Given the same inputs,
always returns the same outputs.
👉 Immutability: State (data) is never modified! Instead,
state is copied and the copy is mutated and returned.
👉 Examples:
FORKIFY APP:
BUILDING A MODERN
APPLICATION
SECTION
LECTURE
FORKIFY APP: BUILDING A MODERN
APPLICATION
PROJECT OVERVIEW AND PLANNING
PROJECT PLANNING
1.
USER STORIES
PLANNING STEP
2.
FEATURES
3.
FLOWCHART
4.
ARCHITECTURE
DEVELOPMENT
STEP
⏳ LATER
1. USER STORIES
1 As a user, I want to search for recipes, so that I can find new ideas for meals
As a user, I want to be able to update the number of servings, so that I can cook a
meal for different number of people
As a user, I want to bookmark recipes, so that I can review them later
As a user, I want to be able to create my own recipes, so that I have them all
organized in the same app
As a user, I want to be able to see my bookmarks and own recipes when I leave the
app and come back later, so that I can close the app safely after cooking
👉 User story: Description of the application’s functionality from the user’s perspective.
👉 Common format: As a [type of user], I want [an action] so that [a bene
fi
t]
2
3
4
5
2. FEATURES
1
2
3
4
5
👉 Search functionality: input field to send request to API with searched
keywords
👉 Display results with pagination
👉 Display recipe with cooking time, servings and ingredients
USER STORIES FEATURES
Search for recipes
Update the number of servings
Bookmark recipes
Create my own recipes
See my bookmarks and own recipes
when I leave the app and come back later
👉 Store bookmark data in the browser using local storage
👉 On page load, read saved bookmarks from local storage and display
👉 Change servings functionality: update all ingredients according to
current number of servings
👉 Bookmarking functionality: display list of all bookmarked recipes
👉 User can upload own recipes
👉 User recipes will automatically be bookmarked
👉 User can only see their own recipes, not recipes from other users
3. FLOWCHART (PART 1)
1. Search functionality: API
search request
2. Results with pagination
3. Display recipe
FEATURES
Other features later
1
2
3
SECTION
LECTURE
FORKIFY APP: BUILDING A MODERN
APPLICATION
THE MVC ARCHITECTURE
WHY WORRY ABOUT ARCHITECTURE?
STRUCTURE
MAINTAINABILITY EXPANDABILITY
👉 A project is never done!
We need to be able to easily
change it in the future
👉 We also need to be able to
easily add new features
👉 Like a house, software
needs a structure: the way
we organize our code
The perfect architecture
👉 We can create our own
architecture (Mapty project)
👉 We can use a well-established
architecture pattern like MVC,
MVP, Flux, etc. (this project)
👉 We can use a framework like
React, Angular, Vue, Svelte, etc.
COMPONENTS OF ANY ARCHITECTURE
HTTP LIBRARY
BUSINESS LOGIC
APPLICATION LOGIC
(ROUTER)
PRESENTATION LOGIC
(UI LAYER)
STATE
👉 Code that solves
the actual business
problem;
👉 Directly related to
what business does
and what it needs;
👉 Example: sending
messages, storing
transactions,
calculating taxes, …
👉 Code that is only
concerned about
the implementation
of application itself;
👉 Handles navigation
and UI events
👉 Code that is
concerned about
the visible part of
the application
👉 Essentially displays
application state
👉 Responsible for
making and
receiving AJAX
requests
👉 Optional but almost
always necessary in
real-world apps
👉 Essentially stores
all the data about
the application
👉 Should be the
“single source of
truth”
👉 UI should be kept in
sync with the state
👉 State libraries exist
Keeping in sync
THE MODEL-VIEW-CONTROLLER (MVC) ARCHITECTURE
MODEL CONTROLLER VIEW
WEB
👉 Bridge between model
and views (which don’t
know about one another)
👉 Handles UI events and
dispatches tasks to
model and view
USER
1
2 2
3
4 4
5
HTTP LIBRARY
BUSINESS LOGIC APPLICATION LOGIC PRESENTATION LOGIC
STATE
Connected by function call and import
Data flow
0
MODEL, VIEW AND CONTROLLER IN FORKIFY (RECIPE DISPLAY ONLY)
CONT-
ROLLER
TO
REMOVE
VIEW
MODEL
0
MVC IMPLEMENTATION (RECIPE DISPLAY ONLY)
0
2
2
4
4
5
3
1
0
SECTION
LECTURE
FORKIFY APP: BUILDING A MODERN
APPLICATION
EVENT HANDLERS IN MVC:
PUBLISHER-SUBSCRIBER PATTERN
EVENT HANDLING IN MVC: PUBLISHER-SUBSCRIBER PATTERN
👉 Events should be handled in the controller (otherwise we would have application logic in the view)
👉 Events should be listened for in the view (otherwise we would need DOM elements in the controller)
0
1
2 3
4
👉 controlRecipes will be passed into addHandlerRender when program starts
👉 addHandlerRender listens for events (addEventListener), and uses
controlRecipes as callback
Code that knows when
to react: PUBLISHER
Code that wants to
react: SUBSCRIBER
Subscribe to publisher by passing in
the subscriber function
A() B
A(X) X
B
C
≠
SECTION
LECTURE
FORKIFY APP: BUILDING A MODERN
APPLICATION
WRAPPING UP: FINAL
CONSIDERATIONS
IMPROVEMENT AND FEATURE IDEAS: CHALLENGES 🤓
👉 Display number of pages between the pagination buttons;
👉 Ability to sort search results by duration or number of ingredients;
👉 Perform ingredient validation in view, before submitting the form;
👉 Improve recipe ingredient input: separate in multiple fields and allow more
than 6 ingredients;
👉 Shopping list feature: button on recipe to add ingredients to a list;
👉 Weekly meal planning feature: assign recipes to the next 7 days and show
on a weekly calendar;
👉 Get nutrition data on each ingredient from spoonacular API (https://
spoonacular.com/food-api) and calculate total calories of recipe.
END

Js basics

  • 1.
    slides for theory lectures (DON’TSKIP THEM, THEY ARE SUPER IMPORTANT 🤓) Subscribe here Follow me here
  • 2.
    📖 TABLE OFCONTENTS: THEORY LECTURES (CLICK THE TITLES) Watch before you start! A Brief Introduction to JavaScript Data Types Boolean Logic JavaScript Releases: ES5, ES6+ and ESNext Functions Calling Other Functions Reviewing Functions Learning How to Code How to Think Like a Developer Debugging (Fixing Errors) What's the DOM and DOM Manipulation An high-level Overview of JavaScript The JavaScript Engine and Runtime Execution Contexts and The Call Stack Scope and The Scope Chain Variable environment: Hoisting and The TDZ The this Keyword Primitives vs. Objects (Primitive vs. Reference Types) Summary: Which Data Structure to Use? First-Class and Higher-Order Functions Closures Data Transformations: map, filter, reduce Summary: Which Array Method to Use? How the DOM Really Works Event Propagation: Bubbling and Capturing Efficient Script Loading: defer and async What is Object-Oriented Programming? OOP in JavaScript Prototypal Inheritance and The Prototype Chain Object.create Inheritance Between "Classes": Constructor Functions Inheritance Between "Classes": Object.create ES6 Classes summary Mapty Project: How to Plan a Web Project Mapty Project: Final Considerations Asynchronous JavaScript, AJAX and APIs How the Web Works: Requests and Responses Promises and the Fetch API Asynchronous Behind the Scenes: The Event Loop An Overview of Modern JavaScript Development An Overview of Modules in JavaScript Modern, Clean and Declarative JavaScript Programming Forkify: Project Overview and Planning The MVC Architecture Event Handlers in MVC: Publisher-Subscriber Pattern Forkify Project: Final Considerations 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
  • 4.
  • 5.
  • 6.
    SOME QUICK CONSIDERATIONSBEFORE WE START... 🚀 ✌ This course is for all of you! So please don’t write a bad review right away if the course is too easy, or too hard, or progressing too slow, or too fast for you. To make it perfect for YOU, you can rewatch lectures, jump to other sections, watch the course with slower or faster playback speed, or ask questions. Please don’t be that person. Everyone is different… (Unless the course itself is truly terrible)
  • 7.
    SOME QUICK CONSIDERATIONSBEFORE WE START... 🚀 👩💻 You need to code along with me! You will learn ZERO JavaScript skills by just sitting and watching me code. You have to code YOURSELF!
  • 8.
    SOME QUICK CONSIDERATIONSBEFORE WE START... 🚀 🤓 Try all the coding challenges! Try to do your best, but if you get stuck for too long, watch the solution. Don’t beat yourself up if you can’t figure it out! Just rewatch the lectures that were covered in the challenge, try to understand them better, and move on. Watch for this sign!
  • 9.
    SOME QUICK CONSIDERATIONSBEFORE WE START... 🚀 📝 If you want the course material to stick, take notes. Notes on code syntax, notes on theory concepts, notes on everything! Totally non-coding... Try to understand a single word 😂
  • 10.
    SOME QUICK CONSIDERATIONSBEFORE WE START... 🚀 😱 If this is your first time ever programming, please don’t get overwhelmed. It’s 100% normal that you will not understand everything at the beginning. Just don’t think “I guess coding is not for me”!
  • 11.
    SOME QUICK CONSIDERATIONSBEFORE WE START... 🚀 😅 In the first sections of the course, don’t bother understanding WHY things work the way they do in JavaScript. Also, don’t stress about efficient code, or fast code, or clean code. While learning, we just want to make things WORK. We will understand the WHY later in the course.
  • 12.
    SOME QUICK CONSIDERATIONSBEFORE WE START... 🚀 ⏳ Before moving on from a section, make sure that you understand exactly what was covered. Take a break, review the code we wrote, review your notes, review the projects we built, and maybe even write some code yourself. ✅ ✅ ✅
  • 13.
    SOME QUICK CONSIDERATIONSBEFORE WE START... 🚀 ⁉ If you have an error or a question, start by trying to solve it yourself! This is essential for your progress. If you can’t solve it, check the Q&A section. If that doesn’t help, just ask a new question. Use a short description, and post relevant code. 1 2 3 😲
  • 14.
    SOME QUICK CONSIDERATIONSBEFORE WE START... 🚀 🖥 I recorded this course on a Mac, but everything works the exact same way on Windows or Linux. If something doesn’t work on your computer, it’s NOT because you’re using a different OS.
  • 15.
    SOME QUICK CONSIDERATIONSBEFORE WE START... 🚀 😍 Most importantly, have fun! It’s so rewarding to see something that YOU have built YOURSELF! So if you’re feeling frustrated, stop whatever you’re doing, and come back later! And I mean REAL fun 😅
  • 17.
  • 18.
    SECTION LECTURE JAVASCRIPT FUNDAMENTALS –PART 1 A BRIEF INTRODUCTION TO JAVASCRIPT
  • 19.
    WHAT IS JAVASCRIPT? JAVASCRIPTIS A HIGH-LEVEL, OBJECT-ORIENTED, MULTI-PARADIGM PROGRAMMING LANGUAGE. JAVASCRIPT 🤯 Instruct computer to do things We don’t have to worry about complex stuff like memory management We can use different styles of programming Based on objects, for storing most kinds of data
  • 20.
    NOUNS THE ROLE OFJAVASCRIPT IN WEB DEVELOPMENT CONTENT PRESENTATION PROGRAMMING LANGUAGE: BUILDING WEB APPLICATIONS p {color: red} means “the paragraph text is red” <p></p> means “paragraph” VERBS p.hide(); means “hide the paragraph” ADJECTIVES
  • 21.
    EXAMPLE OF DYNAMICEFFECTS / WEB APPLICATION Show spinner + loading data in the background Show data after loading Display user info on hover Show spinner + loading data in the background Display tweets after loading data Show tweet box after clicking
  • 22.
    THIS COURSE THERE ISNOTHING YOU CAN’T DO WITH JAVASCRIPT (WELL, ALMOST…) Dynamic effects and web applications in the browser 😍 Web applications on web servers Native mobile applications Native desktop applications 100% based on JavaScript. They might go away, but JavaScript won’t! Back-end apps Front-end apps
  • 23.
    JAVASCRIPT RELEASES... (MOREABOUT THIS LATER) ES5 ES6/ ES2015 ES7/ ES2016 ES8/ ES2017 ES9/ ES2018 ES10/ ES2019 ... Biggest update to the language EVER New updates to JS every single year ES11/ ES2020 ... 🔥 Learn modern JavaScript from the beginning, but without forgetting the older parts! 🥳 Let’s finally get started! ECMAScript Modern JavaScript
  • 25.
  • 26.
    OBJECTS AND PRIMITIVES VALUE OBJECTPRIMITIVE EVERYTHING ELSE OR
  • 27.
    THE 7 PRIMITIVEDATA TYPES 1. Number: Floating point numbers 👉 Used for decimals and integers 2. String: Sequence of characters 👉 Used for text 3. Boolean: Logical type that can only be true or false 👉 Used for taking decisions 4. Undefined: Value taken by a variable that is not yet de fi ned (‘empty value’) 5. Null: Also means ‘empty value’ 6. Symbol (ES2015): Value that is unique and cannot be changed [Not useful for now] 7. BigInt (ES2020): Larger integers than the Number type can hold ☝ JavaScript has dynamic typing: We do not have to manually de fi ne the data type of the value stored in a variable. Instead, data types are determined automatically. Value has type, NOT variable!
  • 29.
  • 30.
    A OR B “Sarahhas a driver’s license OR good vision” OR TRUE FALSE TRUE TRUE TRUE FALSE TRUE FALSE A B BASIC BOOLEAN LOGIC: THE AND, OR & NOT OPERATORS AND TRUE FALSE TRUE TRUE FALSE FALSE FALSE FALSE A B A AND B “Sarah has a driver’s license AND good vision” true when ALL are true 👇 true when ONE is true 👇 No matter how many variables NOT A, NOT B Inverts true/false value 👇 A: Sarah has a driver’s license B: Sarah has good vision 👉 EXAMPLE: Boolean variables that can be either TRUE or FALSE Possible values Results of operation, depending on 2 variables
  • 31.
    AN EXAMPLE 👩💻 👉A: Age is greater or equal 20 👉 B: Age is less than 30 OR TRUE FALSE TRUE TRUE TRUE FALSE TRUE FALSE A B AND TRUE FALSE TRUE TRUE FALSE FALSE FALSE FALSE A B false true age = 16 BOOLEAN VARIABLES LET’S USE OPERATORS! 👉 !A 👉 A AND B 👉 A OR B 👉 !A AND B 👉 A OR !B true false true true false false true false true true true false false false
  • 33.
    SECTION LECTURE JAVASCRIPT FUNDAMENTALS –PART 1 JAVASCRIPT RELEASES: ES5, ES6+ AND ESNEXT
  • 34.
    A BRIEF HISTORYOF JAVASCRIPT 1995 👉 Brendan Eich creates the very first version of JavaScript in just 10 days. It was called Mocha, but already had many fundamental features of modern JavaScript! 👉 Mocha changes to LiveScript and then to JavaScript, in order to attract Java developers. However, JavaScript has almost nothing to do with Java ☝ 👉 Microsoft launches IE, copying JavaScript from Netscape and calling it JScript; 👉 With a need to standardize the language, ECMA releases ECMAScript 1 (ES1), the fi rst official standard for JavaScript (ECMAScript is the standard, JavaScript the language in practice); 👉 ES5 (ECMAScript 5) is released with lots of great new features; 👉 ES6/ES2015 (ECMAScript 2015) was released: the biggest update to the language ever! 👉 ECMAScript changes to an annual release cycle in order to ship less features per update 🙏 👉 Release of ES2016 / ES2017 / ES2018 / ES2019 / ES2020 / ES2021 / … / ES2089 😅 1996 1997 2009 2015 2016 – ∞
  • 35.
    BACKWARDS COMPATIBILITY: DON’TBREAK THE WEB! 1997 Modern JavaScript Engine 2020 👍 BACKWARDS COMPATIBLE 😂 Modern JavaScript Engine 2020 2089 👎 NOT FORWARDS COMPATIBLE DON’T BREAK THE WEB! 👉 Old features are never removed; 👉 Not really new versions, just incremental updates (releases) 👉 Websites keep working forever!
  • 36.
    HOW TO USEMODERN JAVASCRIPT TODAY 👉 Fully supported in all browsers (down to IE 9 from 2011); 👉 Ready to be used today 👍 ES5 👉 ES6+: Well supported in all modern browsers; 👉 No support in older browsers; 👉 Can use most features in production with transpiling and polyfilling 😃 ES6/ES2015 ↓ ES2020 👉 ESNext: Future versions of the language (new feature proposals that reach Stage 4); 👉 Can already use some features in production with transpiling and polyfilling. ES2021 – ∞ http://kangax.github.io/compat-table (As of 2020) 👩💻 During development: Simply use the latest Google Chrome! 🚀 During production: Use Babel to transpile and poly fi ll your code (converting back to ES5 to ensure browser compatibility for all users). Will add new videos
  • 37.
    3 reasons whywe should not forget the Good Ol’ JavaScript: MODERN JAVASCRIPT FROM THE BEGINNING 👉 You will better understand how JavaScript actually works; 👉 Many tutorials and code you fi nd online today are still in ES5; 👉 When working on old codebases, these will be written in ES5. 🔥 Learn modern JavaScript from the beginning! ☝ But, also learn how some things used to be done before modern JavaScript (e.g. const & let vs var and function constructors vs ES6 class).
  • 39.
  • 40.
    SECTION LECTURE JAVASCRIPT FUNDAMENTALS –PART 2 FUNCTIONS CALLING OTHER FUNCTIONS
  • 41.
    CALLING A FUNCTIONINSIDE A FUNCTION: DATA FLOW 2 2 2 2 8 8 8 3
  • 43.
  • 44.
    FUNCTIONS REVIEW; 3DIFFERENT FUNCTION TYPES 👉 Function declaration Function that can be used before it’s declared 👉 Function expression Essentially a function value stored in a variable 👉 Arrow function Great for a quick one-line functions. Has no this keyword (more later...) ☝ Three different ways of writing functions, but they all work in a similar way: receive input data, transform data, and then output data.
  • 45.
    FUNCTIONS REVIEW: ANATOMYOF A FUNCTION Arguments: actual values of function parameters, to input data Variable to save returned value (function output) Calling, running or invoking the function, using () return statement to output a value from the function and terminate execution Parameters: placeholders to receive input values. Like local variables of a function Function body: block of code that we want to reuse. Processes the function’s input data Function name
  • 47.
  • 48.
    SECTION LECTURE DEVELOPER SKILLS &EDITOR SETUP LEARNING HOW TO CODE
  • 49.
    HOW TO FAIL🤦 AT LEARNING HOW TO CODE 💥 He didn’t have a clear goal at the beginning of his journey 💥 He started by watching courses and reading tutorials, but he would just copy the code without caring how it works. Sometimes he would just copy and paste code! 💥 He didn’t reinforce what he was learning by doing small challenges or taking notes 💥 He didn’t practice coding, and didn’t come up with his own project ideas 💥 He quickly became frustrated when his code was not perfectly clean or efficient 💥 He lost motivation because he thought he could never know everything 💥 He was learning in isolation 💥 After finishing a couple of courses, he thought he now was a web developer and could start applying to jobs. But he couldn’t even build an app on his own! John (not actually…)
  • 50.
    HOW TO SUCCEED🎉 AT LEARNING HOW TO CODE 💥 He would just copy the code without caring how it works. Sometimes he would just copy and paste code! 👍 Understand the code that you’re studying and typing 👍 Always type the code, don’t copy-paste! 💥 He didn’t reinforce what he was learning by doing small challenges or taking notes FIX 💥 He didn’t have a clear goal at the beginning of his journey 👍 Set a specific, measurable, realistic and time-based goal 👍 Know exactly why you are learning to code: Switching careers? Finding a better job? 👍 Imagine a big project you want to be able to build! 👍 Research technologies you need and then learn them FIX 👍 After you learn a new feature or concept, use it immediately 👍 Take notes 👍 Challenge yourself and practice with small coding exercises and challenges 👍 Don’t be in a hurry to complete the course fast! FIX
  • 51.
    HOW TO SUCCEED🎉 AT LEARNING HOW TO CODE 💥 He didn’t practice coding, and didn’t come up with his own project ideas FIX 👍 Practicing on your own is the most important thing to do 👍 This is NOT optional! Without practice outside of courses, you won’t go anywhere! 👍 Come up with your own project ideas or copy popular sites or applications, or just parts of them in the beginning 👍 Don’t be stuck in “tutorial hell” 💥 He lost motivation because he thought he could never know everything FIX 👍 Embrace the fact that you will never you know everything 👍 Just focus on what you need to achieve your goal! 💥 He quickly became frustrated when his code was not perfectly clean or efficient FIX 👍 Don’t get stuck trying to write the perfect code! 👍 Just write tons of code, no matter the quality! 👍 Clean and efficient code will come with time 👍 You can always refactor code later
  • 52.
    HOW TO SUCCEED🎉 AT LEARNING HOW TO CODE 💥 After finishing a couple of courses, he thought he now was a web developer and could start applying to jobs FIX 👍 The biggest misconception that people have! 👍 Courses are an amazing starting point, but are only the beginning of your journey! 💥 He was learning in isolation FIX 👍 Explain new concepts to other people. If you can explain it, you truly understand it! 👍 Share your goals to make yourself accountable 👍 Share your learning progress with the web dev community (#100DaysOfCode, #CodeNewbie, #webdev, etc.) NEXT SLIDE
  • 53.
    LEARNING HOW TOCODE IS HARD, BUT YOU CAN DO IT! Source: https://www.thinkful.com/blog/why-learning-to-code-is-so-damn-hard/ Study courses: understand code, take challenges and notes Stay motivated! Keep writing lots of code on your own, no matter how bad Learn with other people, devs and beginners, and share progress Keep challenging yourself, run into lots of problems, and fix them Round up your skillset with best practices and tools (git, testing, …) JOB READY (But the learning never stops 😅) Cliff of confusion Back to awesome Pit of despair Competence Confidence JOB READY Everything is awesome You’re probably somewhere here
  • 55.
    SECTION LECTURE DEVELOPER SKILLS &EDITOR SETUP HOW TO THINK LIKE A DEVELOPER: BECOME A PROBLEM SOLVER!
  • 56.
    HOW TO FAIL🤦 AT SOLVING PROBLEMS 💥 He jumps at the problem without much thinking 💥 He implements his solution in an unstructured way 💥 He gets stressed out when things don’t work 💥 He is too proud to research solutions John can code now 😁 FIX 👍 Stay calm and slow down, don’t just jump at a problem without a plan 👍 Take a very logical and rational approach (programming is just logic, in the end…) 👍 Use my 4-step framework to solve any problem NEXT SLIDE WHENEVER JOHN ENCOUNTERS A PROBLEM: 👉 Example: In an array of GPS coordinates, fi nd the two closest points
  • 57.
    4 STEPS TOSOLVE ANY PROBLEM Make sure you 100% understand the problem. Ask the right questions to get a clear picture of the problem 1 EXAMPLE 💬 Project Manager: “We need a function that reverses whatever we pass into it” 👉 What does “whatever” even mean in this context? What should be reversed? Answer: Only strings, numbers, and arrays make sense to reverse... 👉 What to do if something else is passed in? 👉 What should be returned? Should it always be a string, or should the type be the same as passed in? 👉 How to recognize whether the argument is a number, a string, or an array? 👉 How to reverse a number, a string, and an array? 1
  • 58.
    4 STEPS TOSOLVE ANY PROBLEM Make sure you 100% understand the problem. Ask the right questions to get a clear picture of the problem 1 Divide and conquer: Break a big problem into smaller sub-problems. 2 EXAMPLE 💬 Project Manager: “We need a function that reverses whatever we pass into it” 👉 Check if argument is a number, a string, or an array 👉 Implement reversing a number 👉 Implement reversing a string 👉 Implement reversing an array 👉 Return reversed value 2 SUB-PROBLEMS: Looks like a task list that we need to implement
  • 59.
    4 STEPS TOSOLVE ANY PROBLEM Make sure you 100% understand the problem. Ask the right questions to get a clear picture of the problem 1 Divide and conquer: Break a big problem into smaller sub-problems. 2 EXAMPLE 💬 Project Manager: “We need a function that reverses whatever we pass into it” 👉 How to check if a value is a number in JavaScript? 👉 How to check if a value is a string in JavaScript? 👉 How to check if a value is an array in JavaScript? 👉 How to reverse a number in JavaScript? 👉 How to reverse a string in JavaScript? 👉 How to reverse an array in JavaScript? 3 Don't be afraid to do as much research as you have to 3
  • 60.
    4 STEPS TOSOLVE ANY PROBLEM Make sure you 100% understand the problem. Ask the right questions to get a clear picture of the problem 1 Divide and conquer: Break a big problem into smaller sub-problems. 2 EXAMPLE 💬 Project Manager: “We need a function that reverses whatever we pass into it” 4 Don't be afraid to do as much research as you have to 3 For bigger problems, write pseudo-code before writing the actual code 4 function reverse(value) if value type !string && !number && !array return value if value type == string reverse string if value type == number reverse number if value type == array reverse array return reversed value
  • 62.
    SECTION LECTURE DEVELOPER SKILLS &EDITOR SETUP DEBUGGING (FIXING ERRORS)
  • 63.
    WHAT IS ASOFTWARE BUG? 👉 Software bug: Defect or problem in a computer program. Basically, any unexpected or unintended behavior of a computer program is a software bug. 👉 Bugs are completely normal in software development! 👉 Previous example: “We need a function that reverses whatever we pass into it” reverse([1, 3, 5, 7]) [5, 1, 7, 3] 👉 Debugging: Process of finding, fixing and preventing bugs. Unexpected result: the array is scrambled, NOT reversed. So there is a bug in the reverse function 🐛 A real bug which was causing an error in Harvard’s computer in the 1940s
  • 64.
    THE DEBUGGING PROCESS IDENTIFY Becomingaware that there is a bug 👉 During development 👉 Testing software 👉 User reports during production 👉 Context: browsers, users, etc. FIND Isolating where exactly the bug is happening in code FIX Correct the bug PREVENT Preventing it from happening again 👉 Searching for the same bug in similar code 👉 Writing tests using testing software 👉 Developer console (simple code) 👉 Debugger (complex code) 👉 Replace wrong solution with new correct solution
  • 66.
    JAVASCRIPT IN THE BROWSER:DOM AND EVENTS FUNDAMENTALS
  • 67.
    SECTION LECTURE JAVASCRIPT IN THEBROWSER: DOM AND EVENTS FUNDAMENTALS WHAT'S THE DOM AND DOM MANIPULATION
  • 68.
    WHAT IS THEDOM? DOCUMENT OBJECT MODEL: STRUCTURED REPRESENTATION OF HTML DOCUMENTS. ALLOWS JAVASCRIPT TO ACCESS HTML ELEMENTS AND STYLES TO MANIPULATE THEM. DOM Change text, HTML attributes, and even CSS styles Tree structure, generated by browser on HTML load
  • 69.
    THE DOM TREESTRUCTURE Special object that is the entry point to the DOM. Example: document.querySelector()
  • 70.
    WEB APIs DOMMethods and Properties DOM != =JAVASCRIPT 🧐 DOM Methods and Properties for DOM Manipulation 👎 NOT PART OF For example document.querySelector() Timers Fetch 👍 CAN INTERACT WITH API: Application Programming Interface
  • 72.
  • 73.
    SECTION LECTURE HOW JAVASCRIPT WORKSBEHIND THE SCENES AN HIGH-LEVEL OVERVIEW OF JAVASCRIPT
  • 74.
    WHAT IS JAVASCRIPT:REVISITED JAVASCRIPT IS A HIGH-LEVEL, OBJECT-ORIENTED, MULTI-PARADIGM PROGRAMMING LANGUAGE. JAVASCRIPT
  • 75.
    WHAT IS JAVASCRIPT:REVISITED JAVASCRIPT IS A HIGH-LEVEL, PROTOTYPE-BASED OBJECT-ORIENTED, MULTI-PARADIGM, INTERPRETED OR JUST-IN-TIME COMPILED, DYNAMIC, SINGLE-THREADED, GARBAGE-COLLECTED PROGRAMMING LANGUAGE WITH FIRST-CLASS FUNCTIONS AND A NON-BLOCKING EVENT LOOP CONCURRENCY MODEL. JAVASCRIPT 🤔 🤯 🤣
  • 76.
    DECONSTRUCTING THE MONSTERDEFINITION High-level Prototype-based object-oriented Multi-paradigm Interpreted or just-in-time compiled Dynamic Single-threaded Garbage-collected First-class functions Non-blocking event loop
  • 77.
    High-level Prototype-based object-oriented Multi-paradigm Interpreted orjust-in-time compiled Dynamic Single-threaded Garbage-collected First-class functions Non-blocking event loop + 👉 Any computer program needs resources: LOW-LEVEL Developer has to manage resources manually HIGH-LEVEL Developer does NOT have to worry, everything happens automatically DECONSTRUCTING THE MONSTER DEFINITION
  • 78.
    High-level Prototype-based object-oriented Multi-paradigm Interpreted orjust-in-time compiled Dynamic Single-threaded Garbage-collected First-class functions Non-blocking event loop 🧹 ✨ Cleaning the memory so we don’t have to DECONSTRUCTING THE MONSTER DEFINITION
  • 79.
    High-level Prototype-based object-oriented Multi-paradigm Interpreted orjust-in-time compiled Dynamic Single-threaded Garbage-collected First-class functions Non-blocking event loop Abstraction over 0s and 1s More about this Later in this Section 👇 CONVERT TO MACHINE CODE = COMPILING DECONSTRUCTING THE MONSTER DEFINITION Happens inside the JavaScript engine
  • 80.
    High-level Prototype-based object-oriented Multi-paradigm Interpreted orjust-in-time compiled Dynamic Single-threaded Garbage-collected First-class functions Non-blocking event loop DECONSTRUCTING THE MONSTER DEFINITION More about this later in Multiple Sections 👉 👉 Paradigm: An approach and mindset of structuring code, which will direct your coding style and technique. 1 Procedural programming 2 Object-oriented programming (OOP) 3 Functional programming (FP) The one we’ve been using so far ☝ Imperative vs. 👋 Declarative
  • 81.
    High-level Prototype-based object-oriented Multi-paradigm Interpreted orjust-in-time compiled Dynamic Single-threaded Garbage-collected First-class functions Non-blocking event loop DECONSTRUCTING THE MONSTER DEFINITION Our array inherits methods from prototype Array.prototype.push Array.prototype.indexOf Built from prototype Array Prototype More about this in Section Object Oriented Programming 👉 (Oversimplification!)
  • 82.
    High-level Prototype-based object-oriented Multi-paradigm Interpreted orjust-in-time compiled Dynamic Single-threaded Garbage-collected First-class functions Non-blocking event loop More about this in Section A Closer Look at Functions 👉 👉 In a language with first-class functions, functions are simply treated as variables. We can pass them into other functions, and return them from functions. Passing a function into another function as an argument: First-class functions! DECONSTRUCTING THE MONSTER DEFINITION
  • 83.
    High-level Prototype-based object-oriented Multi-paradigm Interpreted orjust-in-time compiled Dynamic Single-threaded Garbage-collected First-class functions Non-blocking event loop No data type definitions. Types becomes known at runtime Data type of variable is automatically changed 👉 Dynamically-typed language: DECONSTRUCTING THE MONSTER DEFINITION
  • 84.
    High-level Prototype-based object-oriented Multi-paradigm Interpreted orjust-in-time compiled Dynamic Single-threaded Garbage-collected First-class functions Non-blocking event loop DECONSTRUCTING THE MONSTER DEFINITION 👉 Concurrency model: how the JavaScript engine handles multiple tasks happening at the same time. Why do we need that? 👉 JavaScript runs in one single thread, so it can only do one thing at a time. 👉 Sounds like it would block the single thread. However, we want non-blocking behavior! So what about a long-running task? 👉 By using an event loop: takes long running tasks, executes them in the “background”, and puts them back in the main thread once they are fi nished. How do we achieve that? More about this Later in this Section 👇 (Oversimplification!)
  • 86.
    SECTION LECTURE HOW JAVASCRIPT WORKSBEHIND THE SCENES THE JAVASCRIPT ENGINE AND RUNTIME
  • 87.
    WHAT IS AJAVASCRIPT ENGINE? PROGRAM THAT EXECUTES JAVASCRIPT CODE. JS ENGINE ENGINE 👉 Example: V8 Engine CALL STACK HEAP Object in memory Execution context Where our code is executed Where objects are stored How is it compiled?
  • 88.
    👉 Interpretation: Interpreterruns through the source code and executes it line by line. COMPUTER SCIENCE SIDENOTE: COMPILATION VS. INTERPRETATION 🤓 👉 Compilation: Entire code is converted into machine code at once, and written to a binary fi le that can be executed by a computer. Portable file: machine code Source code STEP 1 COMPILATION Program running STEP 2 EXECUTION Source code STEP 1 EXECUTION LINE BY LINE Program running Can happen way after compilation Code still needs to be converted to machine code Machine code Source code STEP 1 COMPILATION Program running STEP 2 EXECUTION Happens immediately 👉 Just-in-time (JIT) compilation: Entire code is converted into machine code at once, then executed immediately. NOT a portable file
  • 89.
    Optimization MODERN JUST-IN-TIME COMPILATIONOF JAVASCRIPT Compilation Execution Parsing AST Example 👉 AST Example Happens in Call Stack ENGINE Just-in-time compilation Happens in special threads that we can’t access from code During execution! “JavaScript is an interpreted language”
  • 90.
    RUNTIME IN THEBROWSER THE BIGGER PICTURE: JAVASCRIPT RUNTIME ENGINE HEAP CALL STACK CALLBACK QUEUE timer data ... EVENT LOOP WEB APIs DOM Timers Fetch API ... Container including all the things that we need to use JavaScript (in this case in the browser) Example: Callback function from DOM event listener Essential for non-blocking concurrency model onClick click Functionalities provided to the engine, accessible on window object
  • 91.
    RUNTIME IN NODE.JS ENGINE HEAPCALL STACK THE BIGGER PICTURE: JAVASCRIPT RUNTIME CALLBACK QUEUE timer data ... EVENT LOOP WEB APIs click C++ BINDINGS & THREAD POOL
  • 93.
    SECTION LECTURE HOW JAVASCRIPT WORKSBEHIND THE SCENES EXECUTION CONTEXTS AND THE CALL STACK
  • 94.
    EXECUTION Compilation WHAT IS ANEXECUTION CONTEXT? Creation of global execution context (for top-level code) Execution of top-level code (inside global EC) Execution of functions and waiting for callbacks Example: click event callback NOT inside a function 👉 Human-readable code: Function body only executed when called! Environment in which a piece of JavaScript is executed. Stores all the necessary information for some code to be executed. EXECUTION CONTEXT 👉 Exactly one global execution context (EC): Default context, created for code that is not inside any function (top-level). 🍕 📦 🍴 🧾 + + 👉 One execution context per function: For each function call, a new execution context is created. Pizza “execution context” “JavaScript code" All together make the call stack
  • 95.
    second() first() Global EXECUTION CONTEXT INDETAIL WHAT’S INSIDE EXECUTION CONTEXT? 👉 let, const and var declarations 👉 Functions 👉 arguments object 1 Variable Environment 2 Scope chain 3 this keyword Generated during “creation phase”, right before execution NOT in arrow functions! a = 1 b = <unknown> c = 2 arguments = [7, 9] name = ‘Jonas’ first = <function> second = <function> x = <unknown> Array of passed arguments. Available in all “regular” functions (not arrow) Need to run second() first Need to run first() first Literally the function code (Technically, values only become known during execution)
  • 96.
    ENGINE CALL STACK THE CALLSTACK 👉 Compiled code starts execution first() second() Global “Place” where execution contexts get stacked on top of each other, to keep track of where we are in the execution 🗺
  • 98.
    SECTION LECTURE HOW JAVASCRIPT WORKSBEHIND THE SCENES SCOPE AND THE SCOPE CHAIN
  • 99.
    SCOPING AND SCOPEIN JAVASCRIPT: CONCEPTS 👉 Scoping: How our program’s variables are organized and accessed. “Where do variables live?” or “Where can we access a certain variable, and where not?”; 👉 Lexical scoping: Scoping is controlled by placement of functions and blocks in the code; 👉 Scope: Space or environment in which a certain variable is declared (variable environment in case of functions). There is global scope, function scope, and block scope; 👉 Scope of a variable: Region of our code where a certain variable can be accessed. SCOPE CONCEPTS 👉 Variable environment 👉 Scope chain 👉 this keyword EXECUTION CONTEXT
  • 100.
    THE 3 TYPESOF SCOPE FUNCTION SCOPE GLOBAL SCOPE BLOCK SCOPE (ES6) Example: if block, for loop block, etc. 👉 Outside of any function or block 👉 Variables declared in global scope are accessible everywhere 👉 Variables are accessible only inside function, NOT outside 👉 Also called local scope 👉 Variables are accessible only inside block (block scoped) ⚠ HOWEVER, this only applies to let and const variables! 👉 Functions are also block scoped (only in strict mode)
  • 101.
    THE SCOPE CHAIN Globalscope myName = “Jonas” first() scope age = 30 myName = “Jonas” if block scope decade = 3 age = 30 myName = “Jonas” second() scope job = “teacher” age = 30 myName = “Jonas” millennial = true millennial = true SCOPE CHAIN Scope has access to variables from all outer scopes (Considering only variable declarations) millennial = true Variables not in current scope VARIABLE LOOKUP IN SCOPE CHAIN let and const are block-scoped var is function-scoped Global variable
  • 102.
    SCOPE CHAIN VS.CALL STACK CALL STACK Global EC a = “Jonas” first = <function> third = <function> Variable environment (VE) first() EC b = “Hello!” second = <function> second() EC c = “Hi!” third() EC d = “Hey!” first() scope b = “Hello!” second = <function> third() scope d = “Hey!” Global scope a = “Jonas” first = <function> third = <function> a = “Jonas” first = <function> third = <function> a = “Jonas” first = <function> third = <function> second() scope c = “Hi!” a = “Jonas” first = <function> third = <function> b = “Hello!” second = <function> c and b can NOT be found in third() scope! Order in which functions were called SCOPE CHAIN Order in which functions are written in the code ☝ Has nothing to do with order in which functions were called!
  • 103.
    SUMMARY 🥳 👉 Scopingasks the question “Where do variables live?” or “Where can we access a certain variable, and where not?”; 👉 There are 3 types of scope in JavaScript: the global scope, scopes defined by functions, and scopes defined by blocks; 👉 Only let and const variables are block-scoped. Variables declared with var end up in the closest function scope; 👉 In JavaScript, we have lexical scoping, so the rules of where we can access variables are based on exactly where in the code functions and blocks are written; 👉 Every scope always has access to all the variables from all its outer scopes. This is the scope chain! 👉 When a variable is not in the current scope, the engine looks up in the scope chain until it finds the variable it’s looking for. This is called variable lookup; 👉 The scope chain is a one-way street: a scope will never, ever have access to the variables of an inner scope; 👉 The scope chain in a certain scope is equal to adding together all the variable environments of the all parent scopes; 👉 The scope chain has nothing to do with the order in which functions were called. It does not affect the scope chain at all!
  • 105.
    SECTION LECTURE HOW JAVASCRIPT WORKSBEHIND THE SCENES VARIABLE ENVIRONMENT: HOISTING AND THE TDZ
  • 106.
    HOISTING IN JAVASCRIPT 👉Variable environment 👉 Scope chain 👉 this keyword EXECUTION CONTEXT ✅ 👉 Hoisting: Makes some types of variables accessible/usable in the code before they are actually declared. “Variables lifted to the top of their scope”. Before execution, code is scanned for variable declarations, and for each variable, a new property is created in the variable environment object. BEHIND THE SCENES HOISTED? 👇 INITIAL VALUE 👇 SCOPE 👇 function declarations var variables let and const variables function expressions and arrows 🤷 Depends if using var or let/const ✅ YES Actual function Block In strict mode. Otherwise: function! ✅ YES undefined Function 🚫 NO <uninitialized>, TDZ Block Temporal Dead Zone Technically, yes. But not in practice
  • 107.
    TEMPORAL DEAD ZONE,LET AND CONST TEMPORAL DEAD ZONE FOR job VARIABLE ReferenceError: Cannot access 'job' before initialization ReferenceError: x is not defined 👉 Different kinds of error messages: WHY HOISTING? WHY TDZ? 👉 Makes it easier to avoid and catch errors: accessing variables before declaration is bad practice and should be avoided; 👉 Makes const variables actually work 👉 Using functions before actual declaration; 👉 var hoisting is just a byproduct.
  • 109.
    SECTION LECTURE HOW JAVASCRIPT WORKSBEHIND THE SCENES THE THIS KEYWORD
  • 110.
    👉 Method example: 👉Variable environment 👉 Scope chain 👉 this keyword EXECUTION CONTEXT ✅ ✅ HOW THE THIS KEYWORD WORKS ☝ this does NOT point to the function itself, and also NOT the its variable environment! 👉 this keyword/variable: Special variable that is created for every execution context (every function). Takes the value of (points to) the “owner” of the function in which the this keyword is used. ☝ this is NOT static. It depends on how the function is called, and its value is only assigned when the function is actually called. Method 👉 this = <Object that is calling the method> Simple function call 👉 this = undefined Arrow functions 👉 this = <this of surrounding function (lexical this)> Event listener 👉 this = <DOM element that the handler is attached to> new, call, apply, bind 👉 <Later in the course... ⏳> In strict mode! Otherwise: window (in the browser) Don’t get own this jonas calcAge is method 1989 Way better than using jonas.year!
  • 111.
    GOT QUESTIONS? FEEDBACK? JustPOST IT IN THE Q&A OF THIS VIDEO, AND YOU WILL GET HELP THERE!
  • 113.
    SECTION LECTURE HOW JAVASCRIPT WORKSBEHIND THE SCENES PRIMITIVES VS. OBJECTS (PRIMITIVE VS. REFERENCE TYPES)
  • 114.
    REVIEW: PRIMITIVES, OBJECTSAND THE JAVASCRIPT ENGINE ENGINE CALL STACK HEAP PRIMITIVES 👉 Number 👉 String 👉 Boolean 👉 Undefined 👉 Null 👉 Symbol 👉 BigInt OBJECTS 👉 Object literal 👉 Arrays 👉 Functions 👉 Many more… STORED IN STORED IN PRIMITIVE TYPES REFERENCE TYPES
  • 115.
    PRIMITIVE VS. REFERENCEVALUES CALL STACK HEAP 👉 Primitive values example: 👉 Reference values example: 0001 Address Address Value D30F { name: ‘Jonas’; age: 30; } 30 Value 0002 31 0003 oldAge me friend No problem, because we’re NOT changing the value at address 0003! D30F Reference to memory address in Heap age Identifier 27 31
  • 116.
    “HOW JAVASCRIPT WORKSBEHIND THE SCENES” TOPICS FOR LATER... ⏳ 1 Prototypal Inheritance 👉 Object Oriented Programming (OOP) With JavaScript 2 Event Loop 👉 Asynchronous JavaScript: Promises, Async/Await and AJAX 3 How the DOM Really Works 👉 Advanced DOM and Events
  • 118.
  • 119.
    SECTION LECTURE DATA STRUCTURES, MODERN OPERATORSAND STRINGS SUMMARY: WHICH DATA STRUCTURE TO USE?
  • 120.
    👉 JSON dataformat example 1 2 3 SOURCES OF DATA DATA STRUCTURES OVERVIEW Array “Object” “Object” From the program itself: Data written directly in source code (e.g. status messages) From the UI: Data input from the user or data written in DOM (e.g tasks in todo app) From external sources: Data fetched for example from web API (e.g. recipe objects) Data structure Collection of data Arrays or Sets SIMPLE LIST? Objects or Maps KEY/VALUE PAIRS? Application Programming Interface Keys allow us to describe values 👉 Stacks 👉 Queues 👉 Linked lists 👉 Trees 👉 Hash tables NON-BUILT IN: 👉 WeakMap 👉 WeakSet OTHER BUILT-IN:
  • 121.
    ARRAYS SETS VS. ARRAYS VS.SETS AND OBJECTS VS. MAPS OBJECTS MAPS VS. 👉 Use when you need ordered list of values (might contain duplicates) 👉 Use when you need to manipulate data 👉 Use when you need to work with unique values 👉 Use when high-performance is really important 👉 Use to remove duplicates from arrays 👉 Better performance 👉 Keys can have any data type 👉 Easy to iterate 👉 Easy to compute size 👉 More “traditional” key/value store (“abused” objects) 👉 Easier to write and access values with . and [] 👉 Use when you simply need to map key to values 👉 Use when you need keys that are not strings 👉 Use when you need to include functions (methods) 👉 Use when working with JSON (can convert to map)
  • 123.
    A CLOSER LOOKAT FUNCTIONS
  • 124.
    SECTION LECTURE A CLOSER LOOKAT FUNCTIONS FIRST-CLASS AND HIGHER-ORDER FUNCTIONS
  • 125.
    FIRST-CLASS VS. HIGHER-ORDERFUNCTIONS 👉 JavaScript treats functions as first-class citizens 👉 This means that functions are simply values 👉 Functions are just another “type” of object FIRST-CLASS FUNCTIONS 👉 Return functions FROM functions 👉 A function that receives another function as an argument, that returns a new function, or both 👉 This is only possible because of fi rst-class functions HIGHER-ORDER FUNCTIONS 👉 Store functions in variables or properties: 👉 Pass functions as arguments to OTHER functions: 👉 Call methods on functions: 👉 Function that returns new function 2 👉 Function that receives another function 1 Callback function Higher-order function Higher-order function Returned function ✅ 📞 💬
  • 127.
    SECTION LECTURE A CLOSER LOOKAT FUNCTIONS CLOSURES
  • 128.
    “CREATING” A CLOSURE CALLSTACK Global EC secureBooking = <f> booker = <f> secureBooking() scope passengerCount = 0 secureBooking = <f> Global scope secureBooking = <f> Order in which functions were called SCOPE CHAIN Order in which functions are written in the code booker = <f> booker = <f> secureBooking() EC passengerCount = 0 Variable Environment
  • 129.
    UNDERSTANDING CLOSURES CALL STACK GlobalEC secureBooking = <f> booker = <f> secureBooking() scope passengerCount = 0 secureBooking = <f> Global scope secureBooking = <f> SCOPE CHAIN booker() EC <empty> Variable Environment of Execution Context in which booker was created booker() scope secureBooking = <f> booker = <f> <empty> This is the function booker = <f> booker = <f> How to access passengerCount? passengerCount = 0 secureBooking() EC passengerCount = 0
  • 130.
    UNDERSTANDING CLOSURES CALL STACK GlobalEC secureBooking = <f> booker = <f> SCOPE CHAIN booker() scope secureBooking = <f> booker = <f> <empty> passengerCount = 0 CLOSURE 👉 A function has access to the variable environment (VE) of the execution context in which it was created 👉 Closure: VE attached to the function, exactly as it was at the time and place the function was created Global scope secureBooking = <f> booker = <f> This is the function How to access passengerCount? 1 2 (Priority over scope chain) secureBooking() scope passengerCount = 0 secureBooking = <f> booker = <f> booker() EC <empty>
  • 131.
    👉 A closureis the closed-over variable environment of the execution context in which a function was created, even after that execution context is gone; 👉 A closure gives a function access to all the variables of its parent function, even after that parent function has returned. The function keeps a reference to its outer scope, which preserves the scope chain throughout time. 👉 A closure makes sure that a function doesn’t loose connection to variables that existed at the function’s birth place; 👉 A closure is like a backpack that a function carries around wherever it goes. This backpack has all the variables that were present in the environment where the function was created. CLOSURES SUMMARY 🥳 ☝ We do NOT have to manually create closures, this is a JavaScript feature that happens automatically. We can’t even access closed-over variables explicitly. A closure is NOT a tangible JavaScript object. Function Connection Parent scope Variables Function Closure Variables Less formal Less formal Less formal
  • 133.
  • 134.
    SECTION LECTURE WORKING WITH ARRAYS DATATRANSFORMATIONS: MAP, FILTER, REDUCE
  • 135.
    MAP FILTER REDUCE DATATRANSFORMATIONS WITH MAP, FILTER AND REDUCE 👉 map returns a new array containing the results of applying an operation on all original array elements 3 1 4 3 2 6 2 8 6 4 current * 2 Original array 👉 filter returns a new array containing the array elements that passed a speci fi ed test condition 3 1 4 3 2 3 4 3 current > 2 Filtered array 👉 reduce boils (“reduces”) all array elements down to one single value (e.g. adding all elements together) 3 1 4 3 2 3 acc + current Example 1 2 4 8 11 13 Accumulator Reduced value
  • 137.
  • 138.
    WHICH ARRAY METHODTO USE? 🤔 .find 👉 Based on test condition: .indexOf .findIndex 👉 Based on test condition: 👉 Based on value: To mutate original array A new array Know if array includes To just loop array An array index To transform to value An array element A new string .some .includes .every 👉 Based on value: 👉 Based on test condition: .join 👉 Based on separator string: .forEach 👉 Based on callback: (Does not create a new array, just loops over it) .reduce 👉 Based on accumulator: (Boil down array to single value of any type: number, string, boolean, or even new array or object) “I WANT...:” .splice .reverse .sort .push .pop .shift .unshift 👉 Add to original: 👉 Remove from original: (end) (start) (end) (start) (any) 👉 Others: .fill .slice .concat .map .filter .flat .flatMap 👉 Computed from original: 👉 Filtered using condition: (loop) 👉 Portion of original: 👉 Adding original to other: 👉 Flattening the original:
  • 140.
  • 141.
    SECTION LECTURE ADVANCED DOM ANDEVENTS HOW THE DOM REALLY WORKS
  • 142.
    REVIEW: WHAT ISTHE DOM? BROWSER INTERFACE DOM 👉 Allows us to make JavaScript interact with the browser; 👉 We can write JavaScript to create, modify and delete HTML elements; set styles, classes and attributes; and listen and respond to events; 👉 DOM tree is generated from an HTML document, which we can then interact with; 👉 DOM is a very complex API that contains lots of methods and properties to interact with the DOM tree Application Programming Interface .querySelector() / .addEventListener() / .createElement() / .innerHTML / .textContent / .children / etc ... “Types” of DOM objects (next slide) DOM tree Nodes
  • 143.
    HOW THE DOMAPI IS ORGANIZED BEHIND THE SCENES Node (THIS IS NOT A DOM TREE) EventTarget Window HTMLElement HTMLButtonElement HTMLDivElement ... Document .addEventListener() .removeEventListener() Global object, lots of methods and properties, many unrelated to DOM .textContent .childNodes .parentNode .cloneNode() .innerHTML .classList .children .parentElement .append() .remove() .insertAdjacentHTML() .querySelector() .closest() .matches() .scrollIntoView() .setAttribute() INHERITANCE OF METHODS AND PROPERTIES Example: Any HTMLElement will have access to .addEventListener(), .cloneNode() or .closest() methods. Text Comment Element (One different type of HTMLElement per HTML element...) Represented by JavaScript object <p>Paragraph<p> <p>Paragraph<p> <!--Comment--> .querySelector() .createElement() .getElementById()
  • 145.
    SECTION LECTURE ADVANCED DOM ANDEVENTS EVENT PROPAGATION: BUBBLING AND CAPTURING
  • 146.
    1 CAPTURING PHASE 3 BUBBLING PHASE 2 TARGET PHASE Clickevent BUBBLING AND CAPTURING (THIS DOES NOT HAPPEN ON ALL EVENTS)
  • 148.
    SECTION LECTURE ADVANCED DOM ANDEVENTS EFFICIENT SCRIPT LOADING: DEFER AND ASYNC
  • 149.
    DEFER ASYNC REGULAR DEFER AND ASYNCSCRIPT LOADING HEAD BODY END Execute Parsing HTML Fetch script Waiting... Finish parsing HTML Time DOMContentLoaded Parsing HTML Execute Fetch script DOMContentLoaded Execute Parsing HTML Fetch script Waiting Finish parsing HTML DOMContentLoaded Execute Parsing HTML Fetch script DOMContentLoaded 👉 Makes no sense 🤷 👉 Makes no sense 🤷
  • 150.
    REGULAR VS. ASYNCVS. DEFER 👉 Scripts are fetched asynchronously and executed immediately 👉 Usually the DOMContentLoaded event waits for all scripts to execute, except for async scripts. So, DOMContentLoaded does not wait for an async script 👉 Scripts not guaranteed to execute in order 👉 Use for 3rd-party scripts where order doesn’t matter (e.g. Google Analytics) Run Parse HTML Fetch Wait Parse HTML DOMContentLoaded Run Parse HTML Fetch DOMContentLoaded Run Parse HTML Fetch DOMContentLoaded Run Parse HTML Fetch DOMContentLoaded ASYNC IN HEAD DEFER IN HEAD END OF BODY Run Parse HTML Fetch DOMContentLoaded 👉 Scripts are fetched and executed after the HTML is completely parsed 👉 Use if you need to support old browsers 👉 Scripts are fetched asynchronously and executed after the HTML is completely parsed 👉 DOMContentLoaded event fires after defer script is executed 👉 Scripts are executed in order 👉 This is overall the best solution! Use for your own scripts, and when order matters (e.g. including a library) You can, of course, use different strategies for different scripts. Usually a complete web applications includes more than just one script
  • 152.
  • 153.
    SECTION LECTURE OBJECT ORIENTED PROGRAMMING (OOP)WITH JAVASCRIPT WHAT IS OBJECT-ORIENTED PROGRAMMING?
  • 154.
    WHAT IS OBJECT-ORIENTEDPROGRAMMING? (OOP) OOP Style of code, “how” we write and organize code 👉 Object-oriented programming (OOP) is a programming paradigm based on the concept of objects; 👉 We use objects to model (describe) real-world or abstract features; 👉 Objects may contain data (properties) and code (methods). By using objects, we pack data and the corresponding behavior into one block; 👉 In OOP, objects are self-contained pieces/blocks of code; 👉 Objects are building blocks of applications, and interact with one another; 👉 Interactions happen through a public interface (API): methods that the code outside of the object can access and use to communicate with the object; 👉 OOP was developed with the goal of organizing code, to make it more flexible and easier to maintain (avoid “spaghetti code”). E.g. user or todo list item E.g. HTML component or data structure Data Behaviour
  • 155.
    Like a blueprintfrom which we can create new objects CLASSES AND INSTANCES (TRADITIONAL OOP) CLASS Instance Instance Instance Just a representation, NOT actual JavaScript syntax! JavaScript does NOT support real classes like represented here New object created from the class. Like a real house created from an abstract blueprint ☝ Conceptual overview: it works a bit differently in JavaScript. Still important to understand!
  • 156.
    THE 4 FUNDAMENTALOOP PRINCIPLES Abstraction Polymorphism Inheritance Encapsulation The 4 fundamental principles of Object- Oriented Programming 🤔 “How do we actually design classes? How do we model real-world data into classes?”
  • 157.
    PRINCIPLE 1: ABSTRACTION Polymorphism Inheritance Abstraction Encapsulation 👉Abstraction: Ignoring or hiding details that don’t matter, allowing us to get an overview perspective of the thing we’re implementing, instead of messing with details that don’t really matter to our implementation. Real phone Abstracted phone Do we really need all these low-level details? Details have been abstracted away
  • 158.
    PRINCIPLE 2: ENCAPSULATION Polymorphism Inheritance Again,NOT actually JavaScript syntax (the private keyword doesn’t exist) Abstraction Encapsulation 👉 Encapsulation: Keeping properties and methods private inside the class, so they are not accessible from outside the class. Some methods can be exposed as a public interface (API). NOT accessible from outside the class! STILL accessible from within the class! NOT accessible from outside the class! STILL accessible from within the class! 👉 Prevents external code from accidentally manipulating internal properties/state 👉 Allows to change internal implementation without the risk of breaking external code WHY?
  • 159.
    PRINCIPLE 3: INHERITANCE Polymorphism Inheritance Abstraction Encapsulation 👉Inheritance: Making all properties and methods of a certain class available to a child class, forming a hierarchical relationship between classes. This allows us to reuse common logic and to model real-world relationships. PARENT CLASS CHILD CLASS INHERITANCE Inherited OWN methods and properties Inherited CHILD CLASS EXTENDS PARENT CLASS
  • 160.
    PRINCIPLE 4: POLYMORPHISM Inheritance Polymorphism Abstraction Encapsulation 👉Polymorphism: A child class can overwrite a method it inherited from a parent class [it’s more complex that that, but enough for our purposes]. PARENT CLASS CHILD CLASS CHILD CLASS INHERITANCE INHERITANCE Own login method, overwriting login method inherited from User
  • 162.
    SECTION LECTURE OBJECT ORIENTED PROGRAMMING (OOP)WITH JAVASCRIPT OOP IN JAVASCRIPT
  • 163.
    👉 Example: Array “CLASSICALOOP”: CLASSES OOP IN JAVASCRIPT: PROTOTYPES Array.prototype is the prototype of all array objects we create in JavaScript Therefore, all arrays have access to the map method! Class Instance OOP IN JS: PROTOTYPES 👉 Objects (instances) are instantiated from a class, which functions like a blueprint; 👉 Behavior (methods) is copied from class to all instances. Prototype Object INSTANTIATION PROTOTYPAL INHERITANCE/ DELEGATION 👉 Objects are linked to a prototype object; 👉 Prototypal inheritance: The prototype contains methods (behavior) that are accessible to all objects linked to that prototype; 👉 Behavior is delegated to the linked prototype object. Contains methods Can access methods
  • 164.
    3 WAYS OFIMPLEMENTING PROTOTYPAL INHERITANCE IN JAVASCRIPT 🤔 “How do we actually create prototypes? And how do we link objects to prototypes? How can we create new objects, without having classes?” 3 Object.create() 👉 The easiest and most straightforward way of linking an object to a prototype object. 2 ES6 Classes 👉 Modern alternative to constructor function syntax; 👉 “Syntactic sugar”: behind the scenes, ES6 classes work exactly like constructor functions; 👉 ES6 classes do NOT behave like classes in “classical OOP” (last lecture). 1 Constructor functions 👉 Technique to create objects from a function; 👉 This is how built-in objects like Arrays, Maps or Sets are actually implemented. 👉 Abstraction 👉 Encapsulation 👉 Inheritance 👉 Polymorphism ☝ The 4 pillars of OOP are still valid!
  • 166.
    SECTION LECTURE OBJECT ORIENTED PROGRAMMING (OOP)WITH JAVASCRIPT PROTOTYPAL INHERITANCE AND THE PROTOTYPE CHAIN
  • 167.
    🆕 The newoperator: HOW PROTOTYPAL INHERITANCE / DELEGATION WORKS 1 An empty object is created 2 this keyword in constructor function call is set to the new object 3 The new object is linked (__proto__ property) to the constructor function’s prototype property 4 The new object is returned from the constructor function call Object [jonas] PROTOTYPAL INHERITANCE/ DELEGATION Constructor function [Person()] Prototype [Person.prototype] calcAge: function name: ‘Jonas’ birthYear: 1990 __proto__: Person.prototype .__proto__ .prototype .constructor ☝ This is how it works with function constructors and ES6 classes PROTOTYPE CHAIN Always points to an object’s prototype Can’t find calcAge here! NOT of Person, but objects created by Person
  • 168.
    Prototype [Object.prototype] .__proto__ THE PROTOTYPE CHAIN .__proto__ __proto__:null Prototype [Person.prototype] __proto__: Object.prototype Object [jonas] __proto__: Person.prototype null This is an OBJECT itself! Remember, every object in JavaScript has a prototype! Constructor function [Person()] Constructor function [Object()] PROTOTYPE CHAIN Series of links between objects, linked through prototypes (Similar to the scope chain) Built-in constructor function for objects. This is used when we write an object literal: {…} === new Object(…) Can’t find hasOwnProperty here! Can’t find hasOwnProperty here! Here it is!
  • 170.
  • 171.
    Object [steven] name: ‘Steven’ birthYear: 2002 __proto__: PersonProto OBJECT.CREATE CONSTRUCTORFUNCTIONS HOW OBJECT.CREATE WORKS AUTOMATIC Prototype [PersonProto] calcAge: function .__proto__
  • 173.
    SECTION LECTURE OBJECT ORIENTED PROGRAMMING (OOP)WITH JAVASCRIPT INHERITANCE BETWEEN "CLASSES": CONSTRUCTOR FUNCTIONS
  • 174.
    INHERITANCE BETWEEN “CLASSES” Prototype Object Morespecific type of person, ideal as child class Constructor Function Prototype Constructor Function “CLASS” 1 STUDENT “CLASS” 2 PERSON 1 Constructor functions 2 ES6 Classes 3 Object.create() INHERITANCE BETWEEN “CLASSES” ☝ Using class terminology here to make it easier to understand. Child Parent
  • 175.
    Prototype [Person.prototype] .__proto__ INHERITANCE BETWEEN “CLASSES” .__proto__ Prototype [Student.prototype] Object [mike] __proto__: Student.prototype Constructorfunction [Student()] Constructor function [Person()] __proto__: Person.prototype PROTOTYPE CHAIN Create connection manually using Object.create()
  • 176.
  • 177.
    Prototype [Person.prototype] .__proto__ INHERITANCE BETWEEN “CLASSES” .__proto__ __proto__: Object.prototype Prototype [Student.prototype] __proto__: Person.prototype Object [mike] __proto__: Student.prototype Constructorfunction [Student()] Constructor function [Person()] PROTOTYPE CHAIN Can’t find calcAge here! Can’t find calcAge here! null Prototype [Object.prototype] Here it is!
  • 179.
    SECTION LECTURE OBJECT ORIENTED PROGRAMMING (OOP)WITH JAVASCRIPT INHERITANCE BETWEEN "CLASSES": OBJECT.CREATE
  • 180.
    INHERITANCE BETWEEN “CLASSES”:OBJECT.CREATE Prototype [PersonProto] calcAge: function PROTOTYPE CHAIN .__proto__ Prototype [StudentProto] __proto__: PersonProto .__proto__ Object [jay] __proto__: StudentProto Student inherits from Person
  • 182.
    SECTION LECTURE OBJECT ORIENTED PROGRAMMING (OOP)WITH JAVASCRIPT ES6 CLASSES SUMMARY
  • 183.
    Public field (similarto property, available on created object) Private fields (not accessible outside of class) Static public field (available only on class) Call to parent (super) class (necessary with extend). Needs to happen before accessing this Static method (available only on class. Can not access instance properties nor methods, only static ones) Setter method (use _ to set property with same name as method, and also add getter) Getter method Public method Private method (⚠ Might not yet work in your browser. “Fake” alternative: _ instead of #) Creating new object with new operator Referencing private field and method Constructor method, called by new operator. Mandatory in regular class, might be omitted in a child class Child class Parent class Instance property (available on created object) Redefining private field Inheritance between classes, automatically sets prototype 👉 Classes are just “syntactic sugar” over constructor functions 👉 Classes are not hoisted 👉 Classes are first-class citizens 👉 Class body is always executed in strict mode
  • 185.
  • 186.
    SECTION LECTURE MAPTY APP: OOP,GEOLOCATION, EXTERNAL LIBRARIES, AND MORE! HOW TO PLAN A WEB PROJECT
  • 187.
    PROJECT PLANNING 1. USER STORIES PLANNINGSTEP 2. FEATURES 3. FLOWCHART 4. ARCHITECTURE DEVELOPMENT STEP Description of the application’s functionality from the user’s perspective. All user stories put together describe the entire application. Implementation of our plan using code WHAT we will build HOW we will build it
  • 188.
    1. USER STORIES 1 Asa user, I want to log my running workouts with location, distance, time, pace and steps/minute, so I can keep a log of all my running As a user, I want to log my cycling workouts with location, distance, time, speed and elevation gain, so I can keep a log of all my cycling As a user, I want to see all my workouts at a glance, so I can easily track my progress over time As a user, I want to also see my workouts on a map, so I can easily check where I work out the most As a user, I want to see all my workouts when I leave the app and come back later, so that I can keep using there app over time 👉 User story: Description of the application’s functionality from the user’s perspective. 👉 Common format: As a [type of user], I want [an action] so that [a bene fi t] Who? Example: user, admin, etc. What? Why? 2 3 4 5
  • 189.
    2. FEATURES 1 Log myrunning workouts with location, distance, time, pace and steps/minute Log my cycling workouts with location, distance, time, speed and elevation gain See all my workouts at a glance See my workouts on a map See all my workouts when I leave the app and come back later 2 3 4 5 👉 Map where user clicks to add new workout (best way to get location coordinates) 👉 Geolocation to display map at current location (more user friendly) 👉 Form to input distance, time, pace, steps/minute 👉 Form to input distance, time, speed, elevation gain 👉 Display all workouts in a list 👉 Display all workouts on the map 👉 Store workout data in the browser using local storage API 👉 On page load, read the saved data from local storage and display USER STORIES FEATURES
  • 190.
    3. FLOWCHART 1. Geolocationto display map at current location 2. Map where user clicks to add new workout 3. Form to input distance, time, pace, steps/minute 4. Form to input distance, time, speed, elevation gain 5. Display workouts in a list 6. Display workouts on the map 7. Store workout data in the browser 8. On page load, read the saved data and display 9. Move map to workout location on click FEATURES Added later 1 2 3 4 5 6 7 8 9 ☝ In the real-world, you don’t have to come with the final flowchart right in the planning phase. It’s normal that it changes throughout implementation!
  • 191.
    4. ARCHITECTURE FOR NOW,LET’S JUST START CODING 😍
  • 193.
    SECTION LECTURE MAPTY APP: OOP,GEOLOCATION, EXTERNAL LIBRARIES, AND MORE! FINAL CONSIDERATIONS
  • 194.
    10 ADDITIONAL FEATUREIDEAS: CHALLENGES 🤓 👉 Ability to edit a workout; 👉 Ability to delete a workout; 👉 Ability to delete all workouts; 👉 Ability to sort workouts by a certain field (e.g. distance); 👉 Re-build Running and Cycling objects coming from Local Storage; 👉 More realistic error and confirmation messages; 👉 Ability to position the map to show all workouts [very hard]; 👉 Ability to draw lines and shapes instead of just points [very hard]; 👉 Geocode location from coordinates (“Run in Faro, Portugal”) [only after asynchronous JavaScript section]; 👉 Display weather data for workout time and place [only after asynchronous JavaScript section].
  • 196.
  • 197.
    SECTION LECTURE ASYNCHRONOUS JAVASCRIPT: PROMISES, ASYNC/AWAITAND AJAX ASYNCHRONOUS JAVASCRIPT, AJAX AND APIS
  • 198.
    SYNCHRONOUS CODE SYNCHRONOUS THREAD OF EXECUTION 👉Most code is synchronous; 👉 Synchronous code is executed line by line; 👉 Each line of code waits for previous line to finish; 👎 Long-running operations block code execution. BLOCKING Part of execution context that actually executes the code in computer’s CPU
  • 199.
    ASYNCHRONOUS CODE ASYNCHRONOUS THREAD OF EXECUTION CALLBACKWILL RUN AFTER TIMER 👉 Asynchronous code is executed after a task that runs in the “background” finishes; 👍 Asynchronous code is non-blocking; 👉 Execution doesn’t wait for an asynchronous task to finish its work; 👉 Callback functions alone do NOT make code asynchronous! “BACKGROUND” (More on this in the lecture on Event Loop) 👉 Example: Timer with callback Callback does NOT automatically make code asynchronous! Timer running Executed after all other code Asynchronous Coordinating behavior of a program over a period of time
  • 200.
    ASYNCHRONOUS CODE ASYNCHRONOUS THREAD OF EXECUTION CALLBACKWILL RUN AFTER IMAGE LOADS 👉 Asynchronous code is executed after a task that runs in the “background” finishes; 👍 Asynchronous code is non-blocking; 👉 Execution doesn’t wait for an asynchronous task to finish its work; 👉 Callback functions alone do NOT make code asynchronous! “BACKGROUND” (More on this in the lecture on Event Loop) 👉 Example: Asynchronous image loading with event and callback Image loading Asynchronous 👉 Other examples: Geolocation API or AJAX calls addEventListener does NOT automatically make code asynchronous! Coordinating behavior of a program over a period of time
  • 201.
    WHAT ARE AJAXCALLS? CLIENT (e.g. browser) 👩💻 WEB SERVER 🌐 REQUEST RESPONSE Asynchronous JavaScript And XML: Allows us to communicate with remote web servers in an asynchronous way. With AJAX calls, we can request data from web servers dynamically. Asking for some data 🇵🇹 🇫🇮 🇬🇭 Sending data back 🇵🇹 🇫🇮 🇬🇭 (GET / POST / etc.) AJAX Usually a web API
  • 202.
    WHAT IS ANAPI? 👉 Application Programming Interface: Piece of software that can be used by another piece of software, in order to allow applications to talk to each other; 👉 There are be many types of APIs in web development: 👉 “Online” API: Application running on a server, that receives requests for data, and sends data back as response; 👉 We can build our own web APIs (requires back-end development, e.g. with node.js) or use 3rd-party APIs. DOM API Geolocation API Own Class API “Online” API API 👉 Weather data 👉 Data about countries 👉 Flights data 👉 Currency conversion data 👉 APIs for sending email or SMS 👉 Google Maps 👉 Millions of possibilities... There is an API for everything AJAX XML data format ✈ 🌍 JSON data format Most popular API data format Just “API”
  • 204.
    SECTION LECTURE ASYNCHRONOUS JAVASCRIPT: PROMISES, ASYNC/AWAITAND AJAX HOW THE WEB WORKS: REQUESTS AND RESPONSES
  • 205.
    WHAT HAPPENS WHENWE ACCESS A WEB SERVER CLIENT (e.g. browser) 👩💻 WEB SERVER 🌐 REQUEST RESPONSE 👉 Request-response model or Client-server architecture
  • 206.
    WHAT HAPPENS WHENWE ACCESS A WEB SERVER GET /rest/v2/alpha/PT HTTP/1.1 Host: www.google.com User-Agent: Mozilla/5.0 Accept-Language: en-US <BODY> HTTP REQUEST HTTP RESPONSE TCP/IP socket connection 1 DNS DNS LOOKUP 3 4 WEB SERVER 🌐 Start line: HTTP method + request target + HTTP version HTTP request headers (many different possibilities) 2 Request body (only when sending data to server, e.g. POST) HTTP/1.1 200 OK Date: Fri, 18 Jan 2021 Content-Type: text/html Transfer-Encoding: chunked <BODY> Start line: HTTP version + status code + status message HTTP response headers (many different possibilities) Response body (most responses) CLIENT (e.g. browser) 👩💻 h tt ps:/ /restcountries.eu/rest/v2/alpha/ h tt ps:/ /104.27.142.889:443 Protocol (HTTP or HTTPS) Domain name Resource Protocol (HTTP or HTTPS)
  • 208.
  • 209.
    WHAT ARE PROMISES? 👉Promise: An object that is used as a placeholder for the future result of an asynchronous operation. 👉 Promise: A container for an asynchronously delivered value. 👉 Promise: A container for a future value. Less formal Less formal PROMISE 👉 We no longer need to rely on events and callbacks passed into asynchronous functions to handle asynchronous results; 👉 Instead of nesting callbacks, we can chain promises for a sequence of asynchronous operations: escaping callback hell 🎉 Example: Response from AJAX call 🎟 LOTTERY TICKET Promise that I will receive money if I guess correct outcome 🤞 I buy lottery ticket (promise) right now 🔮 Lottery draw happens asynchronously 💰 If correct outcome, I receive money, because it was promised
  • 210.
    THE PROMISE LIFECYCLE 🔮 🎟 LOTTERY TICKET PENDING Beforethe future value is available SETTLED Asynchronous task has fi nished FULFILLED Success! The value is now available REJECTED An error happened 💩 💰 ASYNC TASK 👉 We are able handle these different states in our code! CONSUME PROMISE BUILD PROMISE When we already have a promise. E.g. promise returned from Fetch API E.g. Fetch API returns promise
  • 212.
    SECTION LECTURE ASYNCHRONOUS JAVASCRIPT: PROMISES, ASYNC/AWAITAND AJAX ASYNCHRONOUS BEHIND THE SCENES: THE EVENT LOOP
  • 213.
    REVIEW: JAVASCRIPT RUNTIME “Container”which includes all the pieces necessary to execute JavaScript code “Heart” of the runtime Where object are stored in memory Where code is actually executed APIs provided to the engine Only ONE thread of execution. No multitasking! Ready-to-be-executed callback functions (coming from events) Sends callbacks from queue to call stack 👉 Concurrency model: How JavaScript handles multiple tasks happening at the same time.
  • 214.
    MICROTASKS QUEUE HOW ASYNCHRONOUS JAVASCRIPTWORKS BEHIND THE SCENES CALL STACK fetch() Global Execution context CALLBACK QUEUE EVENT LOOP WEB APIs setTimeout() DOM() ... Another callback Some callback Like callback queue, but for callbacks related to promises. Has priority over callback queue! Execution context addEventListener() Execution context add() Execution context fetch() Execution context then() Execution context el.src callback Execution context fetch callback Execution context log() Execution context querySelector() Fetching data Loading image 🤔 How can asynchronous code be executed in a non-blocking way, if there is only one thread of execution in the engine? Where asynchronous tasks run Decides when each callback is executed: orchestration Loading image 👎
  • 216.
  • 217.
    SECTION LECTURE MODERN JAVASCRIPT DEVELOPMENT: MODULESAND TOOLING AN OVERVIEW OF MODERN JAVASCRIPT DEVELOPMENT
  • 218.
    NODE PACKAGE MANAGER MODERN JAVASCRIPTDEVELOPMENT BUNDLING JAVASCRIPT BUNDLE TRANSPILING/ POLYFILLING PRODUCTION DEVELOPMENT MODULE 3RD-PARTY PACKAGE BUILD PROCESS Convert modern JavaScript back to ES5 Join all modules into one file 👉 Contains open-source packages to include 3rd-party code in our own code (e.g React, jQuery, Leaflet, etc.) 👉 Contains development tools that help build our applications (e.g. live-server, Parcel, Babel, etc.) 3rd party modules Development tools or MODULE Both repository and software
  • 220.
    SECTION LECTURE MODERN JAVASCRIPT DEVELOPMENT: MODULESAND TOOLING AN OVERVIEW OF MODULES IN JAVASCRIPT
  • 221.
    AN OVERVIEW OFMODULES 👉 Reusable piece of code that encapsulates implementation details; 👉 Usually a standalone file, but it doesn’t have to be. MODULE MODULE IMPORT (DEPENDENCY) EXPORT (PUBLIC API) Module code 👉 Compose software: Modules are small building blocks that we put together to build complex applications; 👉 Isolate components: Modules can be developed in isolation without thinking about the entire codebase; 👉 Abstract code: Implement low-level code in modules and import these abstractions into other modules; 👉 Organized code: Modules naturally lead to a more organized codebase; 👉 Reuse code: Modules allow us to easily reuse the same code, even across multiple projects. WHY MODULES?
  • 222.
    Asynchronous 👉 File downloading Scopedto module 👉 Top-level variables Strict mode 👉 Default mode <script type="module"> 👉 HTML linking undefined 👉 Top-level this ✅ YES 👉 Imports and exports NATIVE JAVASCRIPT (ES6) MODULES ES6 MODULE Global SCRIPT “Sloppy” mode <script> window 🚫 NO ☝ Need to happen at top-level Imports are hoisted! Synchronous ES6 MODULES Modules stored in files, exactly one module per file. import and export syntax
  • 223.
    Execution index.js IMPORTING MODULES BEFOREEXECUTION HOW ES6 MODULES ARE IMPORTED Asynchronous downloading math.js Asynchronous downloading dom.js 👉 index.js Linking imports to math.js exports Linking imports to dom.js exports Execution math.js Execution dom.js Parsing index.js 👉 math.js 👉 dom.js Live connection, NOT copies 👉 Modules are imported synchronously 👉 Possible thanks to top-level (“static”) imports, which make imports known before execution 👉 This makes bundling and dead code elimination possible Live connection, NOT copies
  • 225.
    SECTION LECTURE MODERN JAVASCRIPT DEVELOPMENT: MODULESAND TOOLING REVIEW: WRITING CLEAN AND MODERN JAVASCRIPT
  • 226.
    REVIEW: MODERN ANDCLEAN CODE 👉 Write code so that others can understand it 👉 Write code so that you can understand it in 1 year 👉 Avoid too “clever” and overcomplicated solutions 👉 Use descriptive variable names: what they contain 👉 Use descriptive function names: what they do READABLE CODE 👉 Use DRY principle (refactor your code) 👉 Don’t pollute global namespace, encapsulate instead 👉 Don’t use var 👉 Use strong type checks (=== and !==) GENERAL 👉 Generally, functions should do only one thing 👉 Don’t use more than 3 function parameters 👉 Use default parameters whenever possible 👉 Generally, return same data type as received 👉 Use arrow functions when they make code more readable FUNCTIONS OOP 👉 Use ES6 classes 👉 Encapsulate data and don’t mutate it from outside the class 👉 Implement method chaining 👉 Do not use arrow functions as methods (in regular objects)
  • 227.
    REVIEW: MODERN ANDCLEAN CODE 👉 Use early return (guard clauses) 👉 Use ternary (conditional) or logical operators instead of if 👉 Use multiple if instead of if/else-if 👉 Avoid for loops, use array methods instead 👉 Avoid callback-based asynchronous APIs AVOID NESTED CODE ASYNCHRONOUS CODE 👉 Consume promises with async/await for best readability 👉 Whenever possible, run promises in parallel (Promise.all) 👉 Handle errors and promise rejections
  • 229.
    SECTION LECTURE MODERN JAVASCRIPT DEVELOPMENT: MODULESAND TOOLING DECLARATIVE AND FUNCTIONAL JAVASCRIPT PRINCIPLES
  • 230.
    IMPERATIVE VS. DECLARATIVECODE 👉 Programmer explains “HOW to do things” 👉 We explain the computer every single step it has to follow to achieve a result 👉 Example: Step-by-step recipe of a cake 👉 Programmer tells “WHAT do do” 👉 We simply describe the way the computer should achieve the result 👉 The HOW (step-by-step instructions) gets abstracted away 👉 Example: Description of a cake Two fundamentally different ways of writing code (paradigms) DECLARATIVE IMPERATIVE
  • 231.
    FUNCTIONAL PROGRAMMING PRINCIPLES 👉Use array and object destructuring 👉 Use the spread operator (...) 👉 Use the ternary (conditional) operator 👉 Use template literals DECLARATIVE SYNTAX FUNCTIONAL PROGRAMMING TECHNIQUES 👉 Try to avoid data mutations 👉 Use built-in methods that don’t produce side effects 👉 Do data transformations with methods such as .map(), .filter() and .reduce() 👉 Try to avoid side effects in functions: this is of course not always possible! FUNCTIONAL PROGRAMMING 👉 Declarative programming paradigm 👉 Based on the idea of writing software by combining many pure functions, avoiding side effects and mutating data 👉 Side effect: Modification (mutation) of any data outside of the function (mutating external variables, logging to console, writing to DOM, etc.) 👉 Pure function: Function without side effects. Does not depend on external variables. Given the same inputs, always returns the same outputs. 👉 Immutability: State (data) is never modified! Instead, state is copied and the copy is mutated and returned. 👉 Examples:
  • 233.
    FORKIFY APP: BUILDING AMODERN APPLICATION
  • 234.
    SECTION LECTURE FORKIFY APP: BUILDINGA MODERN APPLICATION PROJECT OVERVIEW AND PLANNING
  • 235.
    PROJECT PLANNING 1. USER STORIES PLANNINGSTEP 2. FEATURES 3. FLOWCHART 4. ARCHITECTURE DEVELOPMENT STEP ⏳ LATER
  • 236.
    1. USER STORIES 1As a user, I want to search for recipes, so that I can find new ideas for meals As a user, I want to be able to update the number of servings, so that I can cook a meal for different number of people As a user, I want to bookmark recipes, so that I can review them later As a user, I want to be able to create my own recipes, so that I have them all organized in the same app As a user, I want to be able to see my bookmarks and own recipes when I leave the app and come back later, so that I can close the app safely after cooking 👉 User story: Description of the application’s functionality from the user’s perspective. 👉 Common format: As a [type of user], I want [an action] so that [a bene fi t] 2 3 4 5
  • 237.
    2. FEATURES 1 2 3 4 5 👉 Searchfunctionality: input field to send request to API with searched keywords 👉 Display results with pagination 👉 Display recipe with cooking time, servings and ingredients USER STORIES FEATURES Search for recipes Update the number of servings Bookmark recipes Create my own recipes See my bookmarks and own recipes when I leave the app and come back later 👉 Store bookmark data in the browser using local storage 👉 On page load, read saved bookmarks from local storage and display 👉 Change servings functionality: update all ingredients according to current number of servings 👉 Bookmarking functionality: display list of all bookmarked recipes 👉 User can upload own recipes 👉 User recipes will automatically be bookmarked 👉 User can only see their own recipes, not recipes from other users
  • 238.
    3. FLOWCHART (PART1) 1. Search functionality: API search request 2. Results with pagination 3. Display recipe FEATURES Other features later 1 2 3
  • 240.
    SECTION LECTURE FORKIFY APP: BUILDINGA MODERN APPLICATION THE MVC ARCHITECTURE
  • 241.
    WHY WORRY ABOUTARCHITECTURE? STRUCTURE MAINTAINABILITY EXPANDABILITY 👉 A project is never done! We need to be able to easily change it in the future 👉 We also need to be able to easily add new features 👉 Like a house, software needs a structure: the way we organize our code The perfect architecture 👉 We can create our own architecture (Mapty project) 👉 We can use a well-established architecture pattern like MVC, MVP, Flux, etc. (this project) 👉 We can use a framework like React, Angular, Vue, Svelte, etc.
  • 242.
    COMPONENTS OF ANYARCHITECTURE HTTP LIBRARY BUSINESS LOGIC APPLICATION LOGIC (ROUTER) PRESENTATION LOGIC (UI LAYER) STATE 👉 Code that solves the actual business problem; 👉 Directly related to what business does and what it needs; 👉 Example: sending messages, storing transactions, calculating taxes, … 👉 Code that is only concerned about the implementation of application itself; 👉 Handles navigation and UI events 👉 Code that is concerned about the visible part of the application 👉 Essentially displays application state 👉 Responsible for making and receiving AJAX requests 👉 Optional but almost always necessary in real-world apps 👉 Essentially stores all the data about the application 👉 Should be the “single source of truth” 👉 UI should be kept in sync with the state 👉 State libraries exist Keeping in sync
  • 243.
    THE MODEL-VIEW-CONTROLLER (MVC)ARCHITECTURE MODEL CONTROLLER VIEW WEB 👉 Bridge between model and views (which don’t know about one another) 👉 Handles UI events and dispatches tasks to model and view USER 1 2 2 3 4 4 5 HTTP LIBRARY BUSINESS LOGIC APPLICATION LOGIC PRESENTATION LOGIC STATE Connected by function call and import Data flow 0
  • 244.
    MODEL, VIEW ANDCONTROLLER IN FORKIFY (RECIPE DISPLAY ONLY) CONT- ROLLER TO REMOVE VIEW MODEL 0
  • 245.
    MVC IMPLEMENTATION (RECIPEDISPLAY ONLY) 0 2 2 4 4 5 3 1 0
  • 247.
    SECTION LECTURE FORKIFY APP: BUILDINGA MODERN APPLICATION EVENT HANDLERS IN MVC: PUBLISHER-SUBSCRIBER PATTERN
  • 248.
    EVENT HANDLING INMVC: PUBLISHER-SUBSCRIBER PATTERN 👉 Events should be handled in the controller (otherwise we would have application logic in the view) 👉 Events should be listened for in the view (otherwise we would need DOM elements in the controller) 0 1 2 3 4 👉 controlRecipes will be passed into addHandlerRender when program starts 👉 addHandlerRender listens for events (addEventListener), and uses controlRecipes as callback Code that knows when to react: PUBLISHER Code that wants to react: SUBSCRIBER Subscribe to publisher by passing in the subscriber function A() B A(X) X B C ≠
  • 250.
    SECTION LECTURE FORKIFY APP: BUILDINGA MODERN APPLICATION WRAPPING UP: FINAL CONSIDERATIONS
  • 251.
    IMPROVEMENT AND FEATUREIDEAS: CHALLENGES 🤓 👉 Display number of pages between the pagination buttons; 👉 Ability to sort search results by duration or number of ingredients; 👉 Perform ingredient validation in view, before submitting the form; 👉 Improve recipe ingredient input: separate in multiple fields and allow more than 6 ingredients; 👉 Shopping list feature: button on recipe to add ingredients to a list; 👉 Weekly meal planning feature: assign recipes to the next 7 days and show on a weekly calendar; 👉 Get nutrition data on each ingredient from spoonacular API (https:// spoonacular.com/food-api) and calculate total calories of recipe.
  • 253.