Theory Lectures v2
Theory Lectures v2
Theory Lectures v2
slides for
theory lectures
(DON’T SKIP THEM, THEY ARE SUPER
IMPORTANT 🤓)
Follow me here
📖 TABLE OF CONTENTS: THEORY LECTURES (CLICK THE TITLES)
1 Watch before you start! 19 Summary: Which Data Structure to Use? 37 How the Web Works: Requests and Responses
2 A Brief Introduction to JavaScript 20 First-Class and Higher-Order Functions 38 Promises and the Fetch API
3 Data Types 21 Closures 39 Asynchronous Behind the Scenes: The Event Loop
4 Boolean Logic 22 Data Transformations: map, filter, reduce 40 An Overview of Modern JavaScript Development
5 JavaScript Releases: ES5, ES6+ and ESNext 23 Summary: Which Array Method to Use? 41 An Overview of Modules in JavaScript
6 Functions Calling Other Functions 24 How the DOM Really Works 42 Modern, Clean and Declarative JavaScript Programming
7 Reviewing Functions 25 Event Propagation: Bubbling and Capturing 43 Forkify: Project Overview and Planning
8 Learning How to Code 26 Efficient Script Loading: defer and async 44 The MVC Architecture
9 How to Think Like a Developer 27 What is Object-Oriented Programming? 45 Event Handlers in MVC: Publisher-Subscriber Pattern
11 What's the DOM and DOM Manipulation 29 Prototypal Inheritance and The Prototype Chain
13 The JavaScript Engine and Runtime 31 Inheritance Between "Classes": Constructor Functions
14 Execution Contexts and The Call Stack 32 Inheritance Between "Classes": Object.create
16 Variable environment: Hoisting and The TDZ 34 Mapty Project: How to Plan a Web Project
18 Primitives vs. Objects (Primitive vs. Reference Types) 36 Asynchronous JavaScript, AJAX and APIs
WELCOME, WELCOME,
WELCOME!
SECTION
WELCOME, WELCOME, WELCOME!
LECTURE
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.
👩💻 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.
📝 If you want the course material to stick, take notes. Notes on code syntax, notes on theory concepts, notes on everything!
😱 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.
😲 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!
LECTURE
A BRIEF INTRODUCTION TO
JAVASCRIPT
WHAT IS JAVASCRIPT?
V A S C R I P T
J A
PROGRAMMING LANGUAGE. 🤯
CONTENT NOUNS
<p></p>
means “paragraph”
ADJECTIVES VERBS
p.hide();
p {color: red}
means “hide the
means “the
paragraph”
paragraph text is red”
Modern JavaScript
ECMAScript
🔥 Learn modern JavaScript from the beginning, but without forgetting the older parts!
🥳 Let’s finally get started!
SECTION
JAVASCRIPT FUNDAMENTALS – PART 1
LECTURE
DATA TYPES
OBJECTS AND PRIMITIVES
VALUE
EVERYTHING ELSE
OBJECT OR PRIMITIVE
THE 7 PRIMITIVE DATA TYPES
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 ned (‘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 ne the data type of
the value stored in a variable. Instead, data types are determined automatically.
fi
fi
SECTION
JAVASCRIPT FUNDAMENTALS – PART 1
LECTURE
BOOLEAN LOGIC
BASIC BOOLEAN LOGIC: THE AND, OR & NOT OPERATORS
B
Results of
operation,
depending on 👉 EXAMPLE:
FALSE FALSE FALSE 2 variables FALSE TRUE FALSE
A: Sarah has a driver’s license
B: Sarah has good vision
👇 👇
true when ALL are true true when ONE is true Boolean variables that can
be either TRUE or FALSE
No matter how many variables
AN EXAMPLE 👩💻
A
BOOLEAN VARIABLES age = 16
AND TRUE FALSE
👉 A: Age is greater or equal 20 false
B
LET’S USE OPERATORS! FALSE FALSE FALSE
👉 !A true
false
A
👉 A AND B false
false true
OR TRUE FALSE
👉 A OR B true
false true
B
👉 !A AND B true
true true
SECTION
JAVASCRIPT FUNDAMENTALS – PART 1
LECTURE
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!
1996 👉 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;
1997 👉 With a need to standardize the language, ECMA releases ECMAScript 1 (ES1), the rst official
standard for JavaScript (ECMAScript is the standard, JavaScript the language in practice);
2015 👉 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 🙏
fi
👍
Modern JavaScript
Engine
BACKWARDS
1997 COMPATIBLE 2020
👎
Modern JavaScript 😂
Engine
NOT FORWARDS
2020 COMPATIBLE 2089
🚀 During production: Use Babel to transpile and poly ll your code (converting
back to ES5 to ensure browser compatibility for all users).
http://kangax.github.io/compat-table
👉 ESNext: Future versions of the language (new feature proposals that reach Stage 4);
ES2021 – ∞
👉 Can already use some features in production with transpiling and polyfilling.
(As of 2020)
Will add new videos
fi
☝ 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).
👉 Many tutorials and code you nd online today are still in ES5;
JAVASCRIPT
FUNDAMENTALS –
PART 2
SECTION
JAVASCRIPT FUNDAMENTALS – PART 2
LECTURE
FUNCTIONS CALLING OTHER
FUNCTIONS
CALLING A FUNCTION INSIDE A FUNCTION: DATA FLOW
2
2
8
3
8
8
2
SECTION
JAVASCRIPT FUNDAMENTALS – PART 2
LECTURE
REVIEWING FUNCTIONS
FUNCTIONS REVIEW; 3 DIFFERENT FUNCTION TYPES
👉 Function declaration
👉 Function expression
Essentially a function
value stored in a variable
👉 Arrow function
return statement to
output a value from
the function and
terminate execution
LECTURE
LEARNING HOW TO CODE
HOW TO FAIL 🤦 AT LEARNING HOW TO CODE
💥 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
John 💥 After finishing a couple of courses, he thought he now was a web developer and
(not actually…) could start applying to jobs. But he couldn’t even build an app on his own!
💥 He didn’t have a clear goal at 💥 He would just copy the code 💥 He didn’t reinforce what he
the beginning of his journey without caring how it works. was learning by doing small
Sometimes he would just challenges or taking notes
copy and paste code!
FIX
FIX
👍 Set a specific, measurable, FIX
realistic and time-based goal 👍 After you learn a new feature
👍 Understand the code that or concept, use it immediately
👍 Know exactly why you are
you’re studying and typing
learning to code: Switching 👍 Take notes
careers? Finding a better job? 👍 Always type the code, don’t
👍 Challenge yourself and
👍 Imagine a big project you copy-paste!
practice with small coding
want to be able to build! exercises and challenges
👍 Research technologies you
👍 Don’t be in a hurry to
need and then learn them
complete the course fast!
💥 He didn’t practice coding, and 💥 He quickly became frustrated 💥 He lost motivation because he
didn’t come up with his own when his code was not thought he could never know
project ideas perfectly clean or efficient everything
👍 Practicing on your own is the 👍 Don’t get stuck trying to write 👍 Embrace the fact that you will
most important thing to do the perfect code! never you know everything
👍 This is NOT optional! Without 👍 Just write tons of code, no 👍 Just focus on what you need
practice outside of courses, matter the quality! to achieve your goal!
you won’t go anywhere!
👍 Clean and efficient code will
👍 Come up with your own come with time
project ideas or copy popular
👍 You can always refactor code
sites or applications, or just
later
parts of them in the beginning
Everything
is awesome Stay motivated! Keep writing lots of
JOB READY code on your own, no matter how bad
Cliff of
confusion
Pit of
despair Learn with other people, devs and
Back to beginners, and share progress
Confidence
awesome
JOB READY
(But the learning never stops 😅)
Source: https://www.thinkful.com/blog/why-learning-to-code-is-so-damn-hard/
SECTION
DEVELOPER SKILLS & EDITOR SETUP
LECTURE
HOW TO THINK LIKE A DEVELOPER:
BECOME A PROBLEM SOLVER!
HOW TO FAIL 🤦 AT SOLVING PROBLEMS
👉 Example: In an array of
WHENEVER JOHN ENCOUNTERS A PROBLEM:
GPS coordinates, nd
the two closest points
💥 He jumps at the problem without much thinking
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…)
John can
code now 😁 👍 Use my 4-step framework to solve any problem
NEXT SLIDE
fi
EXAMPLE
Make sure you 100% understand the
1 problem. Ask the right questions to get
a clear picture of the problem 💬 Project Manager: “We need a function
that reverses whatever we pass into it”
EXAMPLE
Make sure you 100% understand the
1 problem. Ask the right questions to get
a clear picture of the problem 💬 Project Manager: “We need a function
that reverses whatever we pass into it”
2 SUB-PROBLEMS:
Divide and conquer: Break a big
2
problem into smaller sub-problems. 👉 Check if argument is a number, a string, or an array
EXAMPLE
Make sure you 100% understand the
1 problem. Ask the right questions to get
a clear picture of the problem 💬 Project Manager: “We need a function
that reverses whatever we pass into it”
EXAMPLE
Make sure you 100% understand the
1 problem. Ask the right questions to get
a clear picture of the problem 💬 Project Manager: “We need a function
that reverses whatever we pass into it”
4 function reverse(value)
Divide and conquer: Break a big
2 if value type !string && !number && !array
problem into smaller sub-problems.
return value
SECTION
DEVELOPER SKILLS & EDITOR SETUP
LECTURE
DEBUGGING (FIXING ERRORS)
WHAT IS A SOFTWARE BUG?
reverse([1, 3, 5, 7])
Unexpected result: the array
is scrambled, NOT reversed.
So there is a bug in the A real bug which was
[5, 1, 7, 3] reverse function 🐛 causing an error in Harvard’s
computer in the 1940s
Isolating where
Becoming aware Preventing it from
exactly the bug is Correct the bug
that there is a bug happening again
happening in code
JAVASCRIPT IN THE
BROWSER: DOM AND
EVENTS
FUNDAMENTALS
SECTION
JAVASCRIPT IN THE BROWSER: DOM
AND EVENTS FUNDAMENTALS
LECTURE
WHAT'S THE DOM AND DOM
MANIPULATION
WHAT IS THE DOM?
DOM
For example
document.querySelector()
LECTURE
AN HIGH-LEVEL OVERVIEW OF
JAVASCRIPT
WHAT IS JAVASCRIPT: REVISITED
V A S C R I P T
J A
JAVASCRIPT IS A HIGH-LEVEL,
OBJECT-ORIENTED, MULTI-PARADIGM
PROGRAMMING LANGUAGE.
WHAT IS JAVASCRIPT: REVISITED
V A S C R I P T
JA
High-level
Garbage-collected
Multi-paradigm
Prototype-based object-oriented
First-class functions
Dynamic
Single-threaded
Garbage-collected
Prototype-based object-oriented
First-class functions
Dynamic
LOW-LEVEL HIGH-LEVEL
Single-threaded
Developer has to manage Developer does NOT have
resources manually to worry, everything
Non-blocking event loop happens automatically
DECONSTRUCTING THE MONSTER DEFINITION
High-level
Garbage-collected
🧹
Interpreted or just-in-time compiled
Multi-paradigm
✨ Cleaning the memory
Prototype-based object-oriented so we don’t have to
First-class functions
Dynamic
Single-threaded
High-level
First-class functions
Dynamic
Single-threaded
More about this Later in this Section 👇
1 Procedural programming
Multi-paradigm
☝ Imperative vs.
2 Object-oriented programming (OOP)
Prototype-based object-oriented 👋 Declarative
3 Functional programming (FP)
First-class functions
Dynamic
Single-threaded
More about this later in Multiple Sections 👉
High-level Prototype
Array
Garbage-collected
Array.prototype.push (Oversimplification!)
Multi-paradigm
Our array Built from prototype
inherits methods
Prototype-based object-oriented from prototype
First-class functions
Dynamic
Single-threaded
More about this in Section Object Oriented Programming 👉
First-class functions
Dynamic
Single-threaded
More about this in Section A Closer Look at Functions 👉
High-level
👉 Dynamically-typed language:
Garbage-collected
Multi-paradigm
First-class functions
Dynamic
Single-threaded
High-level 👉 Concurrency model: how the JavaScript engine handles multiple tasks
happening at the same time.
Garbage-collected
Why do we need that?
Interpreted or just-in-time compiled 👉 JavaScript runs in one single thread, so it can only do one thing at a time.
(Oversimplification!)
First-class functions How do we achieve that?
👉 By using an event loop: takes long running tasks, executes them in the
Dynamic
“background”, and puts them back in the main thread once they are nished.
Single-threaded
LECTURE
THE JAVASCRIPT ENGINE AND
RUNTIME
WHAT IS A JAVASCRIPT ENGINE?
N G I N E ENGINE
JS E
PROGRAM THAT EXECUTES
JAVASCRIPT CODE. Object in
memory
Execution
context
👉 Example: V8 Engine
STEP 1 STEP 2
Portable file: Program
Source code
machine code running
COMPILATION EXECUTION
👉 Interpretation: Interpreter runs through the source code and executes it line by line.
STEP 1
Program
Source code
running
EXECUTION LINE BY LINE
Code still needs to be converted to machine code
👉 Just-in-time (JIT) compilation: Entire code is converted into machine code at once, then executed immediately.
STEP 1 STEP 2
Program
Source code Machine code
running
COMPILATION EXECUTION
fi
MODERN JUST-IN-TIME COMPILATION OF JAVASCRIPT
“JavaScript is an
interpreted language” 👉 AST Example
ENGINE
Happens in special
threads that we can’t Example
Parsing
access from code
AST
Just-in-time
Compilation compilation
Optimization
Execution Happens in
Call Stack
During execution!
THE BIGGER PICTURE: JAVASCRIPT RUNTIME
DOM Timers
CALLBACK QUEUE
onClick
click timer data ...
HEAP CALL STACK
RUNTIME IN NODE.JS
ENGINE
WEB APIs
EVENT LOOP
CALLBACK QUEUE
LECTURE
EXECUTION CONTEXTS AND THE
CALL STACK
WHAT IS AN EXECUTION CONTEXT?
Compilation
EXECUTION CONTEXT
👉 Human-readable code:
Example: click event callback All together make the call stack
EXECUTION CONTEXT IN DETAIL
👉 arguments object a = 1
b = <unknown>
Need to run
second() first
2 Scope chain
NOT in arrow
functions!
3 this keyword second()
c = 2
arguments = [7, 9]
second()
ENGINE
first()
Global
🗺
“Place” where execution contexts get
stacked on top of each other, to keep CALL STACK
track of where we are in the execution
SECTION
HOW JAVASCRIPT WORKS BEHIND THE
SCENES
LECTURE
SCOPE AND THE SCOPE CHAIN
SCOPING AND SCOPE IN JAVASCRIPT: CONCEPTS EXECUTION CONTEXT
👉 Variable environment
👉 Scope chain
👉 this keyword
O N C E P T S
S C O P E C
👉 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 of a variable: Region of our code where a certain variable can be accessed.
👉 Outside of any function or block 👉 Variables are accessible only 👉 Variables are accessible only
inside function, NOT outside inside block (block scoped)
👉 Variables declared in global
scope are accessible everywhere 👉 Also called local scope ⚠ HOWEVER, this only applies to
let and const variables!
age = 30 age = 30
millennial = true millennial = true
Global scope
a = “Jonas”
third() EC first = <function>
third = <function>
d = “Hey!”
SCOPE CHAIN
Global EC
second() scope Order in which functions
a = “Jonas”
c = “Hi!”
are written in the code
first = <function>
third = <function>
b = “Hello!”
second = <function>
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
HOW JAVASCRIPT WORKS BEHIND THE
SCENES
LECTURE
VARIABLE ENVIRONMENT: HOISTING
AND THE TDZ
HOISTING IN JAVASCRIPT
👉 Hoisting: Makes some types of variables accessible/usable in the code before they are EXECUTION CONTEXT
actually declared. “Variables lifted to the top of their scope”. 👉 Variable environment
👉 this keyword
Before execution, code is scanned for variable declarations, and for each variable, a new
property is created in the variable environment object.
function expressions and arrows 🤷 Depends if using var or let/const Temporal Dead Zone
👉 Using functions before actual declaration; 👉 Makes it easier to avoid and catch errors: accessing variables
before declaration is bad practice and should be avoided;
👉 var hoisting is just a byproduct.
👉 Makes const variables actually work
SECTION
HOW JAVASCRIPT WORKS BEHIND THE
SCENES
LECTURE
THE THIS KEYWORD
HOW THE THIS KEYWORD WORKS
👉 this keyword/variable: Special variable that is created for every execution context (every function). EXECUTION CONTEXT
Takes the value of (points to) the “owner” of the function in which the this keyword is used. ✅
👉 Variable environment
✅
👉 Scope chain
☝ this is NOT static. It depends on how the function is called, and its value is only assigned when the 👉 this keyword
👉 Method example:
Method 👉 this = <Object that is calling the method> In strict mode! Otherwise:
window (in the browser)
Don’t get Simple function call 👉 this = undefined
own this
Arrow functions 👉 this = <this of surrounding function (lexical this)>
Event listener 👉 this = <DOM element that the handler is attached to>
☝ this does NOT point to the function itself, and also NOT the its variable environment! Way better than using
jonas.year!
SECTION
HOW JAVASCRIPT WORKS BEHIND THE
SCENES
LECTURE
PRIMITIVES VS. OBJECTS (PRIMITIVE
VS. REFERENCE TYPES)
REVIEW: PRIMITIVES, OBJECTS AND THE JAVASCRIPT ENGINE
👉 Boolean 👉 Functions
STORED IN
👉 Undefined 👉 Many more…
👉 Null
👉 Symbol
PRIMITIVE TYPES
age 0001 30 31 {
name: ‘Jonas’;
D30F age: 30;
}
oldAge 0002 31
👉 Reference values example:
Reference to memory 27
me 0003 D30F address in Heap
No problem, because
we’re NOT changing the
value at address 0003! friend
LECTURE
SUMMARY: WHICH DATA STRUCTURE
TO USE?
DATA STRUCTURES OVERVIEW
1 From the program itself: Data written directly in source code (e.g. status messages) Array
2 From the UI: Data input from the user or data written in DOM (e.g tasks in todo app)
3 From external sources: Data fetched for example from web API (e.g. recipe objects)
“Object”
Application
Programming
Interface
Collection of data
OTHER BUILT-IN:
👉 WeakMap
👉 WeakSet
NON-BUILT IN:
Data structure
👉 Stacks
👉 Queues SIMPLE LIST? KEY/VALUE PAIRS?
👉 Linked lists
👉 Trees Keys allow us to 👉 JSON data format example
👉 Hash tables Arrays or Sets Objects or Maps describe values
👉 Use when you need ordered 👉 Use when you need to work
list of values (might contain with unique values
👉 More “traditional” key/value 👉 Better performance
duplicates)
👉 Use when high-performance
store (“abused” objects)
👉 Keys can have any data type
👉 Use when you need to is really important
manipulate data 👉 Easier to write and access
👉 Easy to iterate
👉 Use to remove duplicates
values with . and []
from arrays 👉 Easy to compute size
A CLOSER LOOK AT
FUNCTIONS
SECTION
A CLOSER LOOK AT FUNCTIONS
LECTURE
FIRST-CLASS AND HIGHER-ORDER
FUNCTIONS
FIRST-CLASS VS. HIGHER-ORDER FUNCTIONS
👉 Functions are just another “type” of object 👉 This is only possible because of rst-class functions
Higher-order Callback
function function
✅📞💬
👉 Pass functions as arguments to OTHER functions:
2
👉 Function that returns new function
Higher-order
👉 Return functions FROM functions function
SECTION
A CLOSER LOOK AT FUNCTIONS
LECTURE
CLOSURES
“CREATING” A CLOSURE
Global scope
secureBooking = <f>
booker = <f>
Variable
Environment
secureBooking() scope
passengerCount = 0
Global EC
secureBooking = <f>
booker = <f>
UNDERSTANDING CLOSURES
secureBooking = <f>
booker = <f>
secureBooking() scope
passengerCount = 0
How to access
CALL STACK passengerCount?
SCOPE CHAIN
UNDERSTANDING CLOSURES
👉 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>
secureBooking() scope
passengerCount = 0
(Priority over
booker() EC scope chain) secureBooking = <f>
booker = <f>
<empty> CLOSURE
This is the function
booker() scope
Global EC
2
1
passengerCount = 0 <empty>
secureBooking = <f>
secureBooking = <f>
booker = <f>
booker = <f>
How to access
CALL STACK passengerCount?
SCOPE CHAIN
CLOSURES SUMMARY 🥳
👉 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;
Less formal
👉 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.
Less formal
👉 A closure makes sure that a function doesn’t loose connection to variables that existed at the function’s birth place;
Less formal
👉 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.
☝ 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.
WORKING WITH
ARRAYS
SECTION
WORKING WITH ARRAYS
LECTURE
DATA TRANSFORMATIONS: MAP, FILTER,
REDUCE
DATA TRANSFORMATIONS WITH MAP, FILTER AND REDUCE
Original array
3 1 4 3 2 3 1 4 3 2 3 1 4 3 2
6 2 8 6 4 3 4 3 13
11
3
8
4
Reduced value
Filtered array
👉 map returns a new array containing 👉 filter returns a new array 👉 reduce boils (“reduces”) all array
the results of applying an operation containing the array elements that elements down to one single value
on all original array elements passed a speci ed test condition (e.g. adding all elements together)
fi
SECTION
WORKING WITH ARRAYS
LECTURE
SUMMARY: WHICH ARRAY METHOD TO
USE?
WHICH ARRAY METHOD TO USE? 🤔 “I WANT...:”
To mutate original array A new array An array index Know if array includes To transform to value
👉 Add to original: 👉 Computed from original: 👉 Based on value: 👉 Based on value: 👉 Based on accumulator:
.unshift (start)
(Boil down array to single
👉 Filtered using condition: 👉 Based on test condition: 👉 Based on test condition:
value of any type: number,
.splice (any)
An array element A new string To just loop array
👉 Adding original to other:
LECTURE
HOW THE DOM REALLY WORKS
REVIEW: WHAT IS THE DOM?
BROWSER
DOM
INTERFACE
Represented by .addEventListener()
JavaScript object
EventTarget .removeEventListener()
.innerHTML .textContent
.classList .childNodes
.children .parentNode Global object, lots
.parentElement .cloneNode() Node Window of methods and
.append() properties, many
.remove() unrelated to DOM INHERITANCE OF
.insertAdjacentHTML()
<p>Paragraph<p> METHODS AND
.querySelector() PROPERTIES
.closest()
.matches()
Element Text Comment Document
.scrollIntoView() Example:
.setAttribute() <p>Paragraph<p> <!--Comment--> .querySelector()
Any HTMLElement will
.createElement() have access to
.getElementById() .addEventListener(),
HTMLElement .cloneNode()
or .closest() methods.
SECTION
ADVANCED DOM AND EVENTS
LECTURE
EVENT PROPAGATION: BUBBLING AND
CAPTURING
BUBBLING AND CAPTURING
Click event
1 3
CAPTURING BUBBLING
PHASE PHASE
LECTURE
EFFICIENT SCRIPT LOADING: DEFER
AND ASYNC
DEFER AND ASYNC SCRIPT LOADING
REGULAR Parsing HTML Waiting... Finish parsing HTML Parsing HTML Fetch script Execute
Parse HTML Fetch Run Parse HTML Wait Parse HTML Parse HTML Run
👉 Scripts are fetched and executed after the 👉 Scripts are fetched asynchronously and 👉 Scripts are fetched asynchronously and
HTML is completely parsed executed immediately executed after the HTML is completely
parsed
👉 Use if you need to support old browsers 👉 Usually the DOMContentLoaded event
waits for all scripts to execute, except for 👉 DOMContentLoaded event fires after
async scripts. So, DOMContentLoaded defer script is executed
does not wait for an async script
👉 Scripts are executed in order
👉 Scripts not guaranteed to execute in order
👉 This is overall the best solution! Use for
👉 Use for 3rd-party scripts where order your own scripts, and when order matters
doesn’t matter (e.g. Google Analytics) (e.g. including a library)
DOMContentLoaded DOMContentLoaded
OBJECT ORIENTED
PROGRAMMING (OOP)
WITH JAVASCRIPT
SECTION
OBJECT ORIENTED PROGRAMMING
(OOP) WITH JAVASCRIPT
LECTURE
WHAT IS OBJECT-ORIENTED
PROGRAMMING?
WHAT IS OBJECT-ORIENTED PROGRAMMING? (OOP)
Style of code, “how” we
write and organize code
OOP
👉 Object-oriented programming (OOP) is a programming paradigm based on the
concept of objects; E.g. user or todo list item
Data
👉 Objects may contain data (properties) and code (methods). By using objects, we
pack data and the corresponding behavior into one block;
👉 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;
Behaviour 👉 OOP was developed with the goal of organizing code, to make it more flexible
and easier to maintain (avoid “spaghetti code”).
new objects
New object created from the class. Like a
real house created from an abstract blueprint
CLASS Instance
Instance
Just a representation,
NOT actual JavaScript
syntax!
The 4 fundamental
principles of Object-
Oriented Programming
Abstraction
Encapsulation
🤔 “How do we actually design classes? How
Inheritance do we model real-world data into classes?”
Polymorphism
PRINCIPLE 1: ABSTRACTION
Abstraction
Encapsulation
Inheritance
PRINCIPLE 3: INHERITANCE
Inherite CHILD CLASS
d
INH
CHI E RI
LD
CL A TAN
SS C E
Abstraction EXT
END
SP
ARE
NT
CL A
Encapsulation SS
Inherited
Inheritance
PARENT CLASS OWN methods
and properties
Polymorphism
INHERITANCE INHERITANCE
Abstraction
Encapsulation
LECTURE
OOP IN JAVASCRIPT
OOP IN JAVASCRIPT: PROTOTYPES
👉 Example: Array
“CLASSICAL OOP”: CLASSES OOP IN JS: PROTOTYPES
Contains
methods
Class Prototype
Array.prototype is the
Instance Object Can access prototype of all array objects
methods we create in JavaScript
Therefore, all arrays have
access to the map method!
👉 Objects (instances) are 👉 Objects are linked to a prototype object;
instantiated from a class, which
👉 Prototypal inheritance: The prototype
functions like a blueprint;
contains methods (behavior) that are
👉 Behavior (methods) is copied from accessible to all objects linked to that
class to all instances. prototype;
🤔 “How do we actually create prototypes? And how do we link objects to ☝ The 4 pillars of OOP
are still valid!
prototypes? How can we create new objects, without having classes?”
👉 Abstraction
👉 Encapsulation
1 Constructor functions 👉 Inheritance
👉 Technique to create objects from a function; 👉 Polymorphism
👉 This is how built-in objects like Arrays, Maps or Sets are actually implemented.
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).
3 Object.create()
👉 The easiest and most straightforward way of linking an object to a prototype object.
SECTION
OBJECT ORIENTED PROGRAMMING
(OOP) WITH JAVASCRIPT
LECTURE
PROTOTYPAL INHERITANCE AND THE
PROTOTYPE CHAIN
HOW PROTOTYPAL INHERITANCE / DELEGATION WORKS
NOT of Person, but objects created by Person
.prototype
Constructor function Prototype 🆕 The new operator:
[Person()] [Person.prototype]
1 An empty object is created
.constructor
calcAge: function
2 this keyword in
constructor function call
is set to the new object
PROTOTYPAL
PROTOTYPE
INHERITANCE/ .__proto__
CHAIN DELEGATION 3 The new object is linked
(__proto__ property) to
the constructor function’s
Object prototype property
[jonas]
4 The new object is
name: ‘Jonas’ returned from the
Can’t find calcAge here! constructor function call
birthYear: 1990
__proto__:
☝ This is how it works with function Person.prototype Always points to an
constructors and ES6 classes object’s prototype
Can’t find
.__proto__ hasOwnProperty
Built-in constructor function here!
for objects. This is used when
Object
we write an object literal:
[jonas]
{…} === new Object(…)
__proto__:
Person.prototype
Can’t find hasOwnProperty here!
SECTION
OBJECT ORIENTED PROGRAMMING
(OOP) WITH JAVASCRIPT
LECTURE
OBJECT.CREATE
HOW OBJECT.CREATE WORKS
calcAge: function
.__proto__
AUTOMATIC
Object
[steven]
OBJECT.CREATE
name: ‘Steven’
birthYear: 2002
__proto__:
PersonProto
SECTION
OBJECT ORIENTED PROGRAMMING
(OOP) WITH JAVASCRIPT
LECTURE
INHERITANCE BETWEEN "CLASSES":
CONSTRUCTOR FUNCTIONS
INHERITANCE BETWEEN “CLASSES”
Parent
“CLASS” 2
Constructor PERSON
Prototype
Function
1 Constructor functions
INHERITANCE BETWEEN “CLASSES”
2 ES6 Classes
Child
Constructor “CLASS” 1 3 Object.create()
Prototype
Function
STUDENT
Prototype
[Person.prototype]
Constructor function
[Person()]
.__proto__
.__proto__
Object
[mike]
__proto__:
Student.prototype
Prototype
[Person.prototype]
Constructor function
[Person()]
Constructor function
[Student()]
Object
[mike]
👍 GOOD 👎 BAD __proto__:
Student.prototype
Prototype
[Student.prototype] PROTOTYPE
Constructor function
CHAIN
[Student()] __proto__:
Person.prototype
Can’t find
calcAge here!
.__proto__
Object
[mike]
__proto__:
Student.prototype
Can’t find calcAge here!
SECTION
OBJECT ORIENTED PROGRAMMING
(OOP) WITH JAVASCRIPT
LECTURE
INHERITANCE BETWEEN "CLASSES":
OBJECT.CREATE
INHERITANCE BETWEEN “CLASSES”: OBJECT.CREATE
Prototype
[PersonProto]
calcAge: function
Student
.__proto__ inherits from
Person
Prototype
[StudentProto] PROTOTYPE
CHAIN
__proto__:
PersonProto
.__proto__
Object
[jay]
__proto__:
StudentProto
SECTION
OBJECT ORIENTED PROGRAMMING
(OOP) WITH JAVASCRIPT
LECTURE
ES6 CLASSES SUMMARY
Public field (similar to property, available on created object) Parent class
Private fields (not accessible outside of class) Inheritance between
Static public field (available only on class) classes, automatically
sets prototype
Call to parent (super) class (necessary with
extend). Needs to happen before accessing this Child class
Instance property (available on created object)
Constructor method,
Redefining private field
called by new operator.
Public method Mandatory in regular
class, might be omitted
in a child class
Getter method
👉 Classes are just
Setter method (use _ to set property with “syntactic sugar” over
same name as method, and also add getter) constructor functions
👉 Classes are not hoisted
Static method (available only on class. Can not access
instance properties nor methods, only static ones) 👉 Classes are first-class
citizens
👉 Class body is always
Creating new object with new operator executed in strict mode
LECTURE
HOW TO PLAN A WEB PROJECT
PROJECT PLANNING
1. 2. 3. 4. DEVELOPMENT
USER STORIES FEATURES FLOWCHART ARCHITECTURE STEP
PLANNING STEP
Implementation of
our plan using code
1. USER STORIES
👉 User story: Description of the application’s functionality from the user’s perspective.
As a user, I want to log my running workouts with location, distance, time, pace and
1
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
2
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
3
over time
As a user, I want to also see my workouts on a map, so I can easily check where I
4
work out the most
As a user, I want to see all my workouts when I leave the app and come back later, so
5
that I can keep using there app over time
fi
2. FEATURES
Log my running workouts with location, 👉 Map where user clicks to add new workout (best way to
1
distance, time, pace and steps/minute get location coordinates)
👉 Geolocation to display map at current location (more user
friendly)
Log my cycling workouts with location,
2 👉 Form to input distance, time, pace, steps/minute
distance, time, speed and elevation gain
3. FLOWCHART
FEATURES
1 2 3 4
1. Geolocation to display
map at current location
4. ARCHITECTURE
LECTURE
FINAL CONSIDERATIONS
10 ADDITIONAL FEATURE IDEAS: CHALLENGES 🤓
👉 Ability to draw lines and shapes instead of just points [very hard];
👉 Display weather data for workout time and place [only after asynchronous
JavaScript section].
ASYNCHRONOUS
JAVASCRIPT:
PROMISES, ASYNC/
AWAIT AND AJAX
SECTION
ASYNCHRONOUS JAVASCRIPT:
PROMISES, ASYNC/AWAIT AND AJAX
LECTURE
ASYNCHRONOUS JAVASCRIPT, AJAX
AND APIS
SYNCHRONOUS CODE
THREAD OF
EXECUTION
BLOCKING
ASYNCHRONOUS CODE
Asynchronous
THREAD OF
“BACKGROUND”
EXECUTION
CALLBACK WILL
RUN AFTER TIMER Timer
running
Executed after
all other code (More on this in the
lecture on Event Loop)
👉 Asynchronous code is executed after a task that runs in the “background” finishes;
ASYNCHRONOUS CODE
Asynchronous
THREAD OF
“BACKGROUND”
EXECUTION
AJAX
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.
Usually a
Asking for some data 🇵🇹 🇫🇮 🇬🇭
web API
👩💻 RESPONSE
🌐
Sending data back 🇵🇹 🇫🇮 🇬🇭
WHAT IS AN API?
API AJAX
👉 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;
XML data JSON data
format format
👉 There are be many types of APIs in web development:
Most popular
DOM API Geolocation API Own Class API “Online” API API data format
Just “API”
👉 Weather data
👉 “Online” API: Application running on a server, that receives
requests for data, and sends data back as response; 👉 Data about countries
an AP I f or 👉 Flights data ✈ 🌍
There is
👉 We can build our own web APIs (requires back-end everything 👉 Currency conversion data
development, e.g. with node.js) or use 3rd-party APIs. 👉 APIs for sending email or SMS
👉 Google Maps
👉 Millions of possibilities...
SECTION
ASYNCHRONOUS JAVASCRIPT:
PROMISES, ASYNC/AWAIT AND AJAX
LECTURE
HOW THE WEB WORKS: REQUESTS
AND RESPONSES
WHAT HAPPENS WHEN WE ACCESS A WEB SERVER
REQUEST
CLIENT WEB
(e.g. browser) SERVER
👩💻 🌐
RESPONSE
GET /rest/v2/alpha/PT HTTP/1.1 Start line: HTTP method + request target + HTTP version
DNS LOOKUP
1 <BODY> Request body (only when sending data to server, e.g. POST)
HTTP REQUEST
3
CLIENT WEB
(e.g. browser) 2 TCP/IP socket connection SERVER
👩💻 🌐
h ps://restcountries.eu/rest/v2/alpha/ 4
HTTP RESPONSE
HTTP/1.1 200 OK Start line: HTTP version + status code + status message
SECTION
ASYNCHRONOUS JAVASCRIPT:
PROMISES, ASYNC/AWAIT AND AJAX
LECTURE
PROMISES AND THE FETCH API
WHAT ARE PROMISES?
PR O M I S E
🎟
result of an asynchronous operation. LOTTERY
Promise that I will
TICKET receive money if I guess
Less formal correct outcome
ASYNC TASK
PENDING SETTLED BUILD
PROMISE
🔮
🎟
LOTTERY
TICKET
FULFILLED REJECTED
CONSUME
PROMISE
Success! The value
is now available
💰 An error 💩
happened
SECTION
ASYNCHRONOUS JAVASCRIPT:
PROMISES, ASYNC/AWAIT AND AJAX
LECTURE
ASYNCHRONOUS BEHIND THE SCENES:
THE EVENT LOOP
REVIEW: JAVASCRIPT RUNTIME
👉 Concurrency model: How JavaScript handles “Container” which includes all the pieces
multiple tasks happening at the same time. necessary to execute JavaScript code
Sends callbacks
from queue to
call stack
Ready-to-be-executed
callback functions
(coming from events)
WEB APIs
fetch()
setTimeout()
Loading image
DOM()
Execution context
add()
log()
...
Fetching data
MODERN JAVASCRIPT
DEVELOPMENT:
MODULES AND
TOOLING
SECTION
MODERN JAVASCRIPT DEVELOPMENT:
MODULES AND TOOLING
LECTURE
AN OVERVIEW OF MODERN
JAVASCRIPT DEVELOPMENT
MODERN JAVASCRIPT DEVELOPMENT
TRANSPILING/ JAVASCRIPT
MODULE BUNDLING
POLYFILLING BUNDLE
3RD-PARTY
PACKAGE
BUILD PROCESS PRODUCTION
DEVELOPMENT or
SECTION
MODERN JAVASCRIPT DEVELOPMENT:
MODULES AND TOOLING
LECTURE
AN OVERVIEW OF MODULES IN
JAVASCRIPT
AN OVERVIEW OF MODULES
MODULE
IMPORT Module code
(DEPENDENCY)
EXPORT
(PUBLIC API)
Parsing index.js
👉 index.js
Asynchronous Asynchronous
Live connection, downloading math.js downloading dom.js 👉 dom.js
NOT copies 👉 math.js
IMPORTING MODULES
Linking imports to Linking imports to
BEFORE EXECUTION
math.js exports dom.js exports
SECTION
MODERN JAVASCRIPT DEVELOPMENT:
MODULES AND TOOLING
LECTURE
REVIEW: WRITING CLEAN AND
MODERN JAVASCRIPT
REVIEW: MODERN AND CLEAN CODE
👉 Write code so that others can understand it 👉 Generally, functions should do only one thing
👉 Write code so that you can understand it in 1 year 👉 Don’t use more than 3 function parameters
👉 Avoid too “clever” and overcomplicated solutions 👉 Use default parameters whenever possible
👉 Use descriptive variable names: what they contain 👉 Generally, return same data type as received
👉 Use descriptive function names: what they do 👉 Use arrow functions when they make code more readable
GENERAL OOP
👉 Don’t pollute global namespace, encapsulate instead 👉 Encapsulate data and don’t mutate it from outside the class
👉 Use strong type checks (=== and !==) 👉 Do not use arrow functions as methods (in regular objects)
👉 Use early return (guard clauses) 👉 Consume promises with async/await for best readability
👉 Use ternary (conditional) or logical operators instead of if 👉 Whenever possible, run promises in parallel (Promise.all)
SECTION
MODERN JAVASCRIPT DEVELOPMENT:
MODULES AND TOOLING
LECTURE
DECLARATIVE AND FUNCTIONAL
JAVASCRIPT PRINCIPLES
IMPERATIVE VS. DECLARATIVE CODE
IMPERATIVE DECLARATIVE
👉 Programmer explains “HOW to do things” 👉 Programmer tells “WHAT do do”
👉 We explain the computer every single step it has to 👉 We simply describe the way the computer should achieve
follow to achieve a result the result
👉 Example: Step-by-step recipe of a cake 👉 The HOW (step-by-step instructions) gets abstracted away
👉 Side effect: Modification (mutation) of any data outside 👉 Try to avoid side effects in functions: this is of course not
of the function (mutating external variables, logging to always possible!
console, writing to DOM, etc.)
👉 Immutability: State (data) is never modified! Instead, 👉 Use the spread operator (...)
state is copied and the copy is mutated and returned.
👉 Use the ternary (conditional) operator
FORKIFY APP:
BUILDING A MODERN
APPLICATION
SECTION
FORKIFY APP: BUILDING A MODERN
APPLICATION
LECTURE
PROJECT OVERVIEW AND PLANNING
PROJECT PLANNING
⏳ LATER
1. 2. 3. 4. DEVELOPMENT
USER STORIES FEATURES FLOWCHART ARCHITECTURE STEP
PLANNING STEP
1. USER STORIES
👉 User story: Description of the application’s functionality from the user’s perspective.
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
2
meal for different number of people
As a user, I want to be able to create my own recipes, so that I have them all
4
organized in the same app
As a user, I want to be able to see my bookmarks and own recipes when I leave the
5
app and come back later, so that I can close the app safely after cooking
fi
2. FEATURES
See my bookmarks and own recipes 👉 User can only see their own recipes, not recipes from other users
5
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
3. FLOWCHART (PART 1)
FEATURES
1. Search functionality: API
search request
3. Display recipe
1
3
Other features later
SECTION
FORKIFY APP: BUILDING A MODERN
APPLICATION
LECTURE
THE MVC ARCHITECTURE
WHY WORRY ABOUT ARCHITECTURE?
MAINTAINABILITY EXPANDABILITY
👉 Code that solves 👉 Essentially stores 👉 Responsible for 👉 Code that is only 👉 Code that is
the actual business all the data about making and concerned about concerned about
problem; the application receiving AJAX the implementation the visible part of
requests of application itself; the application
👉 Directly related to 👉 Should be the
what business does “single source of 👉 Optional but almost 👉 Handles navigation 👉 Essentially displays
and what it needs; truth” always necessary in and UI events application state
real-world apps
👉 Example: sending 👉 UI should be kept in
messages, storing sync with the state
transactions,
👉 State libraries exist
calculating taxes, …
Keeping in sync
3 2 2 0
CONT- TO
MODEL VIEW
ROLLER REMOVE
0
MVC IMPLEMENTATION (RECIPE DISPLAY ONLY)
1
4
4
5
2
0
3 2
0
SECTION
FORKIFY APP: BUILDING A MODERN
APPLICATION
LECTURE
EVENT HANDLERS IN MVC:
PUBLISHER-SUBSCRIBER PATTERN
EVENT HANDLING IN MVC: PUBLISHER-SUBSCRIBER PATTERN
2 3
1 4
≠ B
👉 controlRecipes will be passed into addHandlerRender when program starts
C
👉 addHandlerRender listens for events (addEventListener), and uses
A(X) X
controlRecipes as callback
👉 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)
SECTION
FORKIFY APP: BUILDING A MODERN
APPLICATION
LECTURE
WRAPPING UP: FINAL
CONSIDERATIONS
IMPROVEMENT AND FEATURE IDEAS: CHALLENGES 🤓
👉 Improve recipe ingredient input: separate in multiple fields and allow more
than 6 ingredients;
👉 Weekly meal planning feature: assign recipes to the next 7 days and show
on a weekly calendar;
END