Subscribe here 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 10 Debugging (Fixing Errors) 28 OOP in JavaScript 46 Forkify Project: Final Considerations 11 What's the DOM and DOM Manipulation 29 Prototypal Inheritance and The Prototype Chain 12 An high-level Overview of JavaScript 30 Object.create 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 15 Scope and The Scope Chain 33 ES6 Classes summary 16 Variable environment: Hoisting and The TDZ 34 Mapty Project: How to Plan a Web Project 17 The this Keyword 35 Mapty Project: Final Considerations 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. 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 JAVASCRIPT FUNDAMENTALS – PART 1 LECTURE A BRIEF INTRODUCTION TO JAVASCRIPT WHAT IS JAVASCRIPT? We don’t have to worry about complex stuff like memory management T P I R C S A V A J JAVASCRIPT IS A HIGH-LEVEL, Based on objects, for storing most kinds of data OBJECT-ORIENTED, MULTI-PARADIGM PROGRAMMING LANGUAGE. ๐คฏ Instruct computer to do things We can use different styles of programming THE ROLE OF JAVASCRIPT IN WEB DEVELOPMENT CONTENT NOUNS <p></p> means “paragraph” ADJECTIVES VERBS p {color: red} p.hide(); means “the paragraph text is red” means “hide the paragraph” PRESENTATION PROGRAMMING LANGUAGE: BUILDING WEB APPLICATIONS EXAMPLE OF DYNAMIC EFFECTS / WEB APPLICATION Display user info on hover Show spinner + loading data in the background Show spinner + loading data in the background Show data after loading Show tweet box after clicking Display tweets after loading data THERE IS NOTHING YOU CAN’T DO WITH JAVASCRIPT (WELL, ALMOST…) Front-end apps THIS COURSE Dynamic effects and web applications in the browser ๐ Back-end apps Web applications on web servers 100% based on JavaScript. They might go away, but JavaScript won’t! Native mobile applications Native desktop applications JAVASCRIPT RELEASES... (MORE ABOUT THIS LATER) New updates to JS every single year Biggest update to the language EVER ... ES5 ES6/ ES2015 ES7/ ES2016 ES8/ ES2017 ES9/ ES2018 ES10/ ES2019 Modern JavaScript ECMAScript ๐ฅ Learn modern JavaScript from the beginning, but without forgetting the older parts! ๐ฅณ Let’s finally get started! ES11/ ES2020 ... SECTION JAVASCRIPT FUNDAMENTALS – PART 1 LECTURE DATA TYPES OBJECTS AND PRIMITIVES VALUE EVERYTHING ELSE OBJECT OR PRIMITIVE 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 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 ne the data type of the value stored in a variable. Instead, data types are determined automatically. fi fi Value has type, NOT variable! SECTION JAVASCRIPT FUNDAMENTALS – PART 1 LECTURE BOOLEAN LOGIC BASIC BOOLEAN LOGIC: THE AND, OR & NOT OPERATORS A AND B A OR B NOT A, NOT B “Sarah has a driver’s license AND good vision” “Sarah has a driver’s license OR good vision” ๐ AND TRUE FALSE TRUE TRUE FALSE FALSE FALSE FALSE OR Results of operation, depending on 2 variables Inverts true/false value A B B A Possible values TRUE TRUE FALSE TRUE TRUE FALSE TRUE FALSE ๐ ๐ true when ALL are true true when ONE is true No matter how many variables ๐ EXAMPLE: A: Sarah has a driver’s license B: Sarah has good vision Boolean variables that can be either TRUE or FALSE AN EXAMPLE ๐ฉ๐ป A age = 16 BOOLEAN VARIABLES ๐ B: Age is less than 30 false true B ๐ A: Age is greater or equal 20 false true ๐ A OR !B false false false OR true true false B true ๐ !A AND B true TRUE FALSE A true ๐ A OR B false TRUE true ๐ A AND B false TRUE FALSE FALSE FALSE FALSE LET’S USE OPERATORS! ๐ !A AND TRUE TRUE FALSE TRUE TRUE FALSE TRUE FALSE 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); 2009 ๐ ES5 (ECMAScript 5) is released with lots of great new features; 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 ๐ ๐ Release of ES2016 / ES2017 / ES2018 / ES2019 / ES2020 / ES2021 / … / ES2089 ๐ fi 2016 – ∞ BACKWARDS COMPATIBILITY: DON’T BREAK THE WEB! ๐ 1997 BACKWARDS COMPATIBLE Modern JavaScript Engine 2020 ๐ Old features are never removed; DON’T BREAK THE WEB! ๐ Not really new versions, just incremental updates (releases) ๐ Websites keep working forever! Modern JavaScript Engine 2020 ๐ NOT FORWARDS COMPATIBLE ๐ 2089 HOW TO USE MODERN JAVASCRIPT TODAY ๐ฉ๐ป During development: Simply use the latest Google Chrome! ๐ 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 ES5 ES6/ES2015 ↓ ES2020 ES2021 – ∞ ๐ Fully supported in all browsers (down to IE 9 from 2011); ๐ Ready to be used today ๐ ๐ ES6+: Well supported in all modern browsers; ๐ No support in older browsers; ๐ Can use most features in production with transpiling and polyfilling ๐ ๐ ESNext: Future versions of the language (new feature proposals that reach Stage 4); ๐ Can already use some features in production with transpiling and polyfilling. (As of 2020) fi Will add new videos MODERN JAVASCRIPT FROM THE BEGINNING ๐ฅ 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). 3 reasons why we should not forget the Good Ol’ JavaScript: ๐ You will better understand how JavaScript actually works; ๐ Many tutorials and code you nd online today are still in ES5; fi ๐ When working on old codebases, these will be written 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 2 8 3 8 2 SECTION JAVASCRIPT FUNDAMENTALS – PART 2 LECTURE 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 Function name 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 return statement to output a value from the function and terminate execution Calling, running or invoking the function, using () Variable to save returned value (function output) Arguments: actual values of function parameters, to input data DEVELOPER SKILLS & EDITOR SETUP SECTION DEVELOPER SKILLS & EDITOR SETUP LECTURE 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 John (not actually…) ๐ฅ 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! HOW TO SUCCEED ๐ AT LEARNING HOW TO CODE ๐ฅ He didn’t have a clear goal at the beginning of his journey FIX ๐ 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 ๐ฅ He would just copy the code ๐ฅ He didn’t reinforce what he without caring how it works. was learning by doing small Sometimes he would just challenges or taking notes copy and paste code! FIX FIX ๐ Understand the code that you’re studying and typing ๐ Always type the code, don’t copy-paste! ๐ 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! HOW TO SUCCEED ๐ AT LEARNING HOW TO CODE ๐ฅ 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 FIX FIX FIX ๐ Practicing on your own is the most important thing to do ๐ Don’t get stuck trying to write the perfect code! ๐ Embrace the fact that you will never you know everything ๐ This is NOT optional! Without practice outside of courses, you won’t go anywhere! ๐ Just write tons of code, no matter the quality! ๐ Just focus on what you need to achieve your goal! ๐ 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” ๐ Clean and efficient code will come with time ๐ You can always refactor code later HOW TO SUCCEED ๐ AT LEARNING HOW TO CODE ๐ฅ He was learning in isolation ๐ฅ After finishing a couple of courses, he thought he now was a web developer and 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.) 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! NEXT SLIDE LEARNING HOW TO CODE IS HARD, BUT YOU CAN DO IT! Study courses: understand code, take challenges and notes Everything is awesome JOB READY Cliff of confusion Confidence Pit of despair Back to awesome 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 Competence You’re probably somewhere here Round up your skillset with best practices and tools (git, testing, …) 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 WHENEVER JOHN ENCOUNTERS A PROBLEM: ๐ Example: In an array of GPS coordinates, nd the two closest points ๐ฅ 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 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…) fi John can code now ๐ ๐ Use my 4-step framework to solve any problem NEXT SLIDE 4 STEPS TO SOLVE ANY PROBLEM 1 EXAMPLE Make sure you 100% understand the 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” 1 ๐ 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? 4 STEPS TO SOLVE ANY PROBLEM 1 2 EXAMPLE Make sure you 100% understand the problem. Ask the right questions to get a clear picture of the problem Divide and conquer: Break a big problem into smaller sub-problems. ๐ฌ Project Manager: “We need a function that reverses whatever we pass into it” 2 SUB-PROBLEMS: ๐ 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 Looks like a task list that we need to implement 4 STEPS TO SOLVE ANY PROBLEM 1 2 EXAMPLE Make sure you 100% understand the problem. Ask the right questions to get a clear picture of the problem Divide and conquer: Break a big problem into smaller sub-problems. ๐ฌ Project Manager: “We need a function that reverses whatever we pass into it” 3 ๐ 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? 3 Don't be afraid to do as much research as you have to ๐ How to reverse a number in JavaScript? ๐ How to reverse a string in JavaScript? ๐ How to reverse an array in JavaScript? 4 STEPS TO SOLVE ANY PROBLEM 1 2 EXAMPLE Make sure you 100% understand the problem. Ask the right questions to get a clear picture of the problem Divide and conquer: Break a big problem into smaller sub-problems. ๐ฌ Project Manager: “We need a function that reverses whatever we pass into it” 4 function reverse(value) if value type !string && !number && !array return value if value type == string 3 Don't be afraid to do as much research as you have to reverse string if value type == number reverse number if value type == array reverse array 4 For bigger problems, write pseudo-code before writing the actual code return reversed value SECTION DEVELOPER SKILLS & EDITOR SETUP LECTURE 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] Unexpected result: the array is scrambled, NOT reversed. So there is a bug in the reverse function ๐ ๐ Debugging: Process of finding, fixing and preventing bugs. A real bug which was causing an error in Harvard’s computer in the 1940s THE DEBUGGING PROCESS Isolating where exactly the bug is happening in code Becoming aware that there is a bug IDENTIFY FIND ๐ During development ๐ Developer console ๐ Testing software ๐ User reports during production ๐ Context: browsers, users, etc. (simple code) ๐ Debugger (complex code) Preventing it from happening again Correct the bug FIX ๐ Replace wrong PREVENT ๐ Searching for the solution with new same bug in similar correct solution code ๐ Writing tests using testing software 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? Tree structure, generated by browser on HTML load DOM DOCUMENT OBJECT MODEL: STRUCTURED REPRESENTATION OF HTML DOCUMENTS. ALLOWS JAVASCRIPT TO ACCESS HTML ELEMENTS AND STYLES TO MANIPULATE THEM. Change text, HTML attributes, and even CSS styles THE DOM TREE STRUCTURE Special object that is the entry point to the DOM. Example: document.querySelector() DOM ! ==JAVASCRIPT ๐ง ๐ DOM Methods and Properties for DOM Manipulation NOT PART OF For example document.querySelector() API: Application Programming Interface WEB APIs DOM Methods and Properties Timers Fetch ๐ CAN INTERACT WITH HOW JAVASCRIPT WORKS BEHIND THE SCENES SECTION HOW JAVASCRIPT WORKS BEHIND THE SCENES LECTURE AN HIGH-LEVEL OVERVIEW OF JAVASCRIPT WHAT IS JAVASCRIPT: REVISITED T P I R C S A V A J JAVASCRIPT IS A HIGH-LEVEL, OBJECT-ORIENTED, MULTI-PARADIGM PROGRAMMING LANGUAGE. WHAT IS JAVASCRIPT: REVISITED T P I R C S A V JA 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. ๐ค ๐คฏ ๐คฃ DECONSTRUCTING THE MONSTER DEFINITION High-level Garbage-collected Interpreted or just-in-time compiled Multi-paradigm Prototype-based object-oriented First-class functions Dynamic Single-threaded Non-blocking event loop DECONSTRUCTING THE MONSTER DEFINITION High-level ๐ Any computer program needs resources: Garbage-collected + Interpreted or just-in-time compiled Multi-paradigm Prototype-based object-oriented First-class functions Dynamic LOW-LEVEL Single-threaded Non-blocking event loop HIGH-LEVEL Developer has to manage resources manually Developer does NOT have to worry, everything happens automatically DECONSTRUCTING THE MONSTER DEFINITION High-level Garbage-collected Interpreted or just-in-time compiled Multi-paradigm Prototype-based object-oriented First-class functions Dynamic Single-threaded Non-blocking event loop โจ ๐งน Cleaning the memory so we don’t have to DECONSTRUCTING THE MONSTER DEFINITION High-level Garbage-collected Abstraction over 0s and 1s Interpreted or just-in-time compiled Multi-paradigm CONVERT TO MACHINE CODE = COMPILING Prototype-based object-oriented Happens inside the JavaScript engine First-class functions Dynamic Single-threaded Non-blocking event loop More about this Later in this Section ๐ DECONSTRUCTING THE MONSTER DEFINITION High-level ๐ Paradigm: An approach and mindset of structuring code, which will direct your coding style and technique. Garbage-collected The one we’ve been using so far Interpreted or just-in-time compiled Multi-paradigm Prototype-based object-oriented 1 Procedural programming 2 Object-oriented programming (OOP) 3 Functional programming (FP) โ Imperative vs. ๐ Declarative First-class functions Dynamic Single-threaded Non-blocking event loop More about this later in Multiple Sections ๐ DECONSTRUCTING THE MONSTER DEFINITION Prototype High-level Array Garbage-collected Array.prototype.push Interpreted or just-in-time compiled Multi-paradigm Prototype-based object-oriented (Oversimplification!) Array.prototype.indexOf Our array inherits methods from prototype Built from prototype First-class functions Dynamic Single-threaded Non-blocking event loop More about this in Section Object Oriented Programming ๐ DECONSTRUCTING THE MONSTER DEFINITION High-level Garbage-collected ๐ 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. Interpreted or just-in-time compiled Multi-paradigm Passing a function into another function as an argument: First-class functions! Prototype-based object-oriented First-class functions Dynamic Single-threaded Non-blocking event loop More about this in Section A Closer Look at Functions ๐ DECONSTRUCTING THE MONSTER DEFINITION High-level Garbage-collected Interpreted or just-in-time compiled ๐ Dynamically-typed language: No data type definitions. Types becomes known at runtime Multi-paradigm Prototype-based object-oriented First-class functions Dynamic Single-threaded Non-blocking event loop Data type of variable is automatically changed DECONSTRUCTING THE MONSTER DEFINITION High-level ๐ Concurrency model: how the JavaScript engine handles multiple tasks happening at the same time. Garbage-collected Interpreted or just-in-time compiled Why do we need that? ๐ JavaScript runs in one single thread, so it can only do one thing at a time. So what about a long-running task? Multi-paradigm Prototype-based object-oriented ๐ Sounds like it would block the single thread. However, we want non-blocking behavior! How do we achieve that? First-class functions Dynamic (Oversimplification!) ๐ 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 nished. Single-threaded More about this Later in this Section ๐ fi Non-blocking event loop SECTION HOW JAVASCRIPT WORKS BEHIND THE SCENES LECTURE THE JAVASCRIPT ENGINE AND RUNTIME WHAT IS A JAVASCRIPT ENGINE? E N I G N JS E ENGINE PROGRAM THAT EXECUTES JAVASCRIPT CODE. Object in memory Execution context ๐ Example: V8 Engine CALL STACK How is it compiled? Where our code is executed HEAP Where objects are stored COMPUTER SCIENCE SIDENOTE: COMPILATION VS. INTERPRETATION ๐ค ๐ Compilation: Entire code is converted into machine code at once, and written to a binary le that can be executed by a computer. Source code STEP 1 COMPILATION Portable file: machine code STEP 2 EXECUTION Program running Can happen way after compilation ๐ Interpretation: Interpreter runs through the source code and executes it line by line. STEP 1 Source code Program 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. COMPILATION Machine code STEP 2 EXECUTION Program running Happens immediately NOT a portable file fi Source code STEP 1 MODERN JUST-IN-TIME COMPILATION OF JAVASCRIPT “JavaScript is an interpreted language” ENGINE Happens in special threads that we can’t access from code Example Parsing AST Compilation Just-in-time compilation Optimization Execution During execution! Happens in Call Stack ๐ AST Example THE BIGGER PICTURE: JAVASCRIPT RUNTIME RUNTIME IN THE BROWSER ENGINE Functionalities provided to the engine, accessible on window object Container including all the things that we need to use JavaScript WEB APIs (in this case in the browser) DOM Timers Fetch API ... EVENT LOOP Essential for non-blocking concurrency model CALLBACK QUEUE HEAP CALL STACK onClick click timer data ... Example: Callback function from DOM event listener THE BIGGER PICTURE: JAVASCRIPT RUNTIME RUNTIME IN NODE.JS ENGINE WEB APIs C++ BINDINGS & THREAD POOL EVENT LOOP CALLBACK QUEUE HEAP CALL STACK click timer data ... SECTION HOW JAVASCRIPT WORKS BEHIND THE SCENES LECTURE EXECUTION CONTEXTS AND THE CALL STACK WHAT IS AN EXECUTION CONTEXT? Compilation Human-readable code: Environment in which a piece of JavaScript Creation of global execution context (for top-level code) EXECUTION ๐ EXECUTION CONTEXT NOT inside a function Execution of top-level code (inside global EC) is executed. Stores all the necessary information for some code to be executed. “JavaScript code" ๐ฆ ๐ +๐ด + ๐งพ Pizza “execution context” ๐ Exactly one global execution context (EC): Default context, created for code that is not Function body only executed when called! Execution of functions and waiting for callbacks inside any function (top-level). ๐ One execution context per function: For each function call, a new execution context is created. Example: click event callback All together make the call stack EXECUTION CONTEXT IN DETAIL Global WHAT’S INSIDE EXECUTION CONTEXT? 1 name = ‘Jonas’ first = <function> second = <function> x = <unknown> Need to run first() first Variable Environment ๐ let, const and var declarations Literally the function code first() ๐ Functions a = 1 b = <unknown> ๐ arguments object 2 Scope chain 3 this keyword NOT in arrow functions! Need to run second() first second() c = 2 arguments = [7, 9] Generated during “creation phase”, right before execution Array of passed arguments. Available in all “regular” functions (not arrow) (Technically, values only become known during execution) THE CALL STACK ๐ Compiled code starts execution second() ENGINE first() Global “Place” where execution contexts get stacked on top of each other, to keep track of where we are in the execution CALL STACK ๐บ 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 S T P E C N O C E P O C S ๐ 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. THE 3 TYPES OF SCOPE GLOBAL SCOPE FUNCTION 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 (Considering only variable declarations) Global scope let and const are block-scoped var is function-scoped Variables not in current scope VARIABLE LOOKUP IN SCOPE CHAIN Global variable myName = “Jonas” SCOPE CHAIN first() scope age = 30 millennial = true myName = “Jonas” if block scope Scope has access to variables from all outer scopes second() scope decade = 3 job = “teacher” age = 30 millennial = true age = 30 millennial = true myName = “Jonas” myName = “Jonas” SCOPE CHAIN VS. CALL STACK Global scope a = “Jonas” first = <function> third = <function> third() EC d = “Hey!” second() EC c = “Hi!” first() EC b = “Hello!” second = <function> Global EC a = “Jonas” first = <function> third = <function> c and b can NOT be found in third() scope! CALL STACK Variable environment (VE) Order in which functions were called first() scope b = “Hello!” second = <function> a = “Jonas” first = <function> third = <function> third() scope d = “Hey!” a = “Jonas” first = <function> third = <function> SCOPE CHAIN second() scope c = “Hi!” Order in which functions are written in the code b = “Hello!” second = <function> a = “Jonas” first = <function> third = <function> โ 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 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 ๐ Scope chain โ BEHIND THE SCENES ๐ this keyword Before execution, code is scanned for variable declarations, and for each variable, a new property is created in the variable environment object. HOISTED? INITIAL VALUE SCOPE ๐ ๐ ๐ function declarations โ YES Actual function Block var variables โ YES undefined Function <uninitialized>, TDZ Block In strict mode. Otherwise: function! Technically, yes. But not in practice let and const variables function expressions and arrows ๐ซ NO ๐คท Depends if using var or let/const Temporal Dead Zone TEMPORAL DEAD ZONE, LET AND CONST TEMPORAL DEAD ZONE FOR job VARIABLE ๐ Different kinds of error messages: ReferenceError: Cannot access 'job' before initialization ReferenceError: x is not defined WHY HOISTING? WHY TDZ? ๐ Using functions before actual declaration; ๐ Makes it easier to avoid and catch errors: accessing variables ๐ var hoisting is just a byproduct. before declaration is bad practice and should be avoided; ๐ 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 function is actually called. ๐ this keyword ๐ Method example: Method ๐ this = <Object that is calling the method> Don’t get own this Simple function call ๐ this = undefined In strict mode! Otherwise: window (in the browser) 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... โณ> calcAge is method โ this does NOT point to the function itself, and also NOT the its variable environment! jonas 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 HOW JAVASCRIPT WORKS BEHIND THE SCENES LECTURE PRIMITIVES VS. OBJECTS (PRIMITIVE VS. REFERENCE TYPES) REVIEW: PRIMITIVES, OBJECTS AND THE JAVASCRIPT ENGINE PRIMITIVES OBJECTS ENGINE ๐ Number STORED IN ๐ Object literal ๐ String ๐ Arrays ๐ Boolean ๐ Functions ๐ Undefined STORED IN ๐ Many more… ๐ Null ๐ Symbol REFERENCE TYPES ๐ BigInt CALL STACK PRIMITIVE TYPES HEAP PRIMITIVE VS. REFERENCE VALUES ๐ Primitive values example: Identifier age ๐ Reference values example: oldAge me No problem, because we’re NOT changing the value at address 0003! Address 0001 0002 0003 Value 30 31 31 D30F Address Value { name: ‘Jonas’; age: 30; D30F } Reference to memory address in Heap friend CALL STACK HEAP 27 “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 DATA STRUCTURES, MODERN OPERATORS AND STRINGS LECTURE SUMMARY: WHICH DATA STRUCTURE TO USE? DATA STRUCTURES OVERVIEW SOURCES OF DATA “Object” 1 From the program itself: Data written directly in source code (e.g. status messages) 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) ๐ WeakMap ๐ WeakSet Data structure NON-BUILT IN: ๐ Stacks ๐ Queues ๐ Linked lists ๐ Trees ๐ Hash tables “Object” Application Programming Interface Collection of data OTHER BUILT-IN: Array SIMPLE LIST? Arrays or Sets KEY/VALUE PAIRS? Objects or Maps Keys allow us to describe values ๐ JSON data format example ARRAYS VS. SETS AND OBJECTS VS. MAPS ARRAYS ๐ Use when you need ordered list of values (might contain duplicates) ๐ Use when you need to manipulate data VS. SETS OBJECTS VS. MAPS ๐ Use when you need to work with unique values ๐ Use when high-performance is really important ๐ Use to remove duplicates from arrays ๐ More “traditional” key/value store (“abused” objects) ๐ Easier to write and access values with . and [] ๐ Better performance ๐ Keys can have any data type ๐ Easy to iterate ๐ Easy to compute size ๐ Use when you need to include functions (methods) ๐ Use when working with JSON (can convert to map) ๐ Use when you simply need to map key to values ๐ Use when you need keys that are not strings A CLOSER LOOK AT FUNCTIONS SECTION A CLOSER LOOK AT FUNCTIONS LECTURE FIRST-CLASS AND HIGHER-ORDER FUNCTIONS FIRST-CLASS VS. HIGHER-ORDER FUNCTIONS FIRST-CLASS FUNCTIONS ๐ JavaScript treats functions as first-class citizens ๐ This means that functions are simply values ๐ Functions are just another “type” of object ๐ Store functions in variables or properties: HIGHER-ORDER FUNCTIONS ๐ A function that receives another function as an argument, that returns a new function, or both ๐ This is only possible because of rst-class functions ๐ 1 Function that receives another function Higher-order function ๐ Callback function โ ๐๐ฌ Pass functions as arguments to OTHER functions: ๐ 2 Return functions FROM functions ๐ Call methods on functions: fi ๐ Function that returns new function Higher-order function Returned function SECTION A CLOSER LOOK AT FUNCTIONS LECTURE CLOSURES “CREATING” A CLOSURE Global scope secureBooking = <f> booker = <f> Variable Environment secureBooking() scope passengerCount = 0 secureBooking() EC secureBooking = <f> booker = <f> passengerCount = 0 Global EC secureBooking = <f> booker = <f> CALL STACK Order in which functions were called Order in which functions are written in the code SCOPE CHAIN UNDERSTANDING CLOSURES secureBooking() EC passengerCount = 0 Variable Environment of Execution Context in which booker was created Global scope secureBooking = <f> booker = <f> secureBooking() scope passengerCount = 0 booker() EC secureBooking = <f> booker = <f> <empty> This is the function Global EC secureBooking = <f> booker = <f> CALL STACK booker() scope <empty> secureBooking = <f> booker = <f> How to access 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 scope chain) booker() EC secureBooking = <f> booker = <f> CLOSURE <empty> This is the function Global EC secureBooking = <f> booker = <f> CALL STACK passengerCount = 0 2 1 booker() scope <empty> secureBooking = <f> booker = <f> How to access 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 Function Connection Parent scope Variables ๐ 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. Function Closure Variables โ 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 MAP 4 3 Example 8 6 4 Accumulator current > 2 3 1 4 3 2 REDUCE 1 2 3 FILTER current * 2 6 2 acc + current 2 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 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 the results of applying an operation SECTION WORKING WITH ARRAYS LECTURE SUMMARY: WHICH ARRAY METHOD TO USE? WHICH ARRAY METHOD TO USE? ๐ค To mutate original array ๐ Add to original: An array index ๐ Computed from original: .push (end) .unshift (start) ๐ Remove from original: .pop (end) .shift (start) .splice (any) ๐ Others: A new array .map “I WANT...:” ๐ Based on value: Know if array includes ๐ Based on value: To transform to value ๐ Based on accumulator: .indexOf .includes .reduce ๐ Filtered using condition: ๐ Based on test condition: ๐ Based on test condition: (Boil down array to single .filter .findIndex .some (loop) value of any type: number, string, boolean, or even new array or object) .every ๐ Portion of original: .slice ๐ Adding original to other: .concat An array element ๐ Based on test condition: .find .reverse A new string ๐ Based on separator string: .join To just loop array ๐ Based on callback: .forEach ๐ Flattening the original: .sort .fill .flat .flatMap (Does not create a new array, just loops over it) ADVANCED DOM AND EVENTS SECTION ADVANCED DOM AND EVENTS LECTURE HOW THE DOM REALLY WORKS REVIEW: WHAT IS THE DOM? BROWSER DOM INTERFACE ๐ Allows us to make JavaScript interact with the browser; Nodes ๐ 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; Application Programming Interface ๐ DOM is a very complex API that contains lots of methods and properties to interact with the DOM tree DOM tree .querySelector() / .addEventListener() / .createElement() / .innerHTML / .textContent / .children / etc ... “Types” of DOM objects (next slide) HOW THE DOM API IS ORGANIZED BEHIND THE SCENES Represented by JavaScript object .innerHTML .textContent .classList .childNodes .children .parentNode .parentElement .cloneNode() .addEventListener() EventTarget Node .append() Window .remove() .insertAdjacentHTML() .querySelector() .removeEventListener() Global object, lots of methods and properties, many unrelated to DOM <p>Paragraph<p> .closest() Element .matches() Text Comment INHERITANCE OF METHODS AND PROPERTIES Document Example: .scrollIntoView() <p>Paragraph<p> .setAttribute() <!--Comment--> .querySelector() .createElement() .getElementById() HTMLElement HTMLButtonElement ... HTMLDivElement Any HTMLElement will have access to .addEventListener(), .cloneNode() or .closest() methods. (One different type of HTMLElement per HTML element...) (THIS IS NOT A DOM TREE) SECTION ADVANCED DOM AND EVENTS LECTURE EVENT PROPAGATION: BUBBLING AND CAPTURING BUBBLING AND CAPTURING Click event (THIS DOES NOT HAPPEN ON ALL EVENTS) 1 3 CAPTURING PHASE BUBBLING PHASE 2 TARGET PHASE SECTION ADVANCED DOM AND EVENTS LECTURE EFFICIENT SCRIPT LOADING: DEFER AND ASYNC DEFER AND ASYNC SCRIPT LOADING HEAD REGULAR Parsing HTML Waiting... Parsing HTML Fetch script DEFER Finish parsing HTML Fetch script Execute Time ASYNC BODY END Waiting Execute Parsing HTML Fetch script Parsing HTML Fetch script DOMContentLoaded Finish parsing HTML DOMContentLoaded ๐ Makes no sense ๐คท DOMContentLoaded Execute DOMContentLoaded Execute ๐ Makes no sense ๐คท REGULAR VS. ASYNC VS. DEFER END OF BODY Parse HTML ASYNC IN HEAD Fetch Run Parse HTML Fetch DOMContentLoaded DEFER IN HEAD Wait Parse HTML Parse HTML Run DOMContentLoaded ๐ Scripts are fetched and executed after the HTML is completely parsed ๐ Scripts are fetched asynchronously and executed immediately ๐ Use if you need to support old browsers ๐ Usually the DOMContentLoaded event waits for all scripts to execute, except for async scripts. So, DOMContentLoaded does not wait for an async script You can, of course, use different strategies for different scripts. Usually a complete web applications includes more than just one script ๐ Scripts not guaranteed to execute in order ๐ Use for 3rd-party scripts where order doesn’t matter (e.g. Google Analytics) Parse HTML Fetch DOMContentLoaded Fetch Run DOMContentLoaded ๐ 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) Parse HTML Run Fetch Run 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 Data concept of objects; E.g. user or todo list item ๐ We use objects to model (describe) real-world or abstract features; E.g. HTML component or data structure ๐ 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; Behaviour ๐ OOP was developed with the goal of organizing code, to make it more flexible and easier to maintain (avoid “spaghetti code”). CLASSES AND INSTANCES (TRADITIONAL OOP) โ Conceptual overview: it works Like a blueprint from which we can create new objects CLASS a bit differently in JavaScript. Still important to understand! Instance New object created from the class. Like a real house created from an abstract blueprint Instance Instance Just a representation, NOT actual JavaScript syntax! JavaScript does NOT support real classes like represented here THE 4 FUNDAMENTAL OOP PRINCIPLES Abstraction Encapsulation Inheritance Polymorphism The 4 fundamental principles of ObjectOriented Programming ๐ค “How do we actually design classes? How do we model real-world data into classes?” PRINCIPLE 1: ABSTRACTION Real phone Abstracted phone Abstraction Encapsulation Inheritance Polymorphism Do we really need all these low-level details? ๐ 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. Details have been abstracted away PRINCIPLE 2: ENCAPSULATION NOT accessible from outside the class! Abstraction Encapsulation Inheritance STILL accessible from within the class! STILL accessible from within the class! NOT accessible from outside the class! Polymorphism Again, NOT actually JavaScript syntax (the private keyword doesn’t exist) WHY? ๐ Prevents external code from accidentally manipulating internal properties/state ๐ Allows to change internal implementation without the risk of breaking external code ๐ 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). PRINCIPLE 3: INHERITANCE Inherite CHI Abstraction LD INH CL A SS E RI EXT END TAN C d E SP ARE Encapsulation CHILD CLASS NT CL A SS Inherited Inheritance PARENT CLASS Polymorphism OWN methods and properties ๐ 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. PRINCIPLE 4: POLYMORPHISM INHERITANCE INHERITANCE Abstraction Encapsulation Inheritance PARENT CLASS Own login method, overwriting login method inherited from User Polymorphism CHILD CLASS CHILD CLASS ๐ 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]. SECTION OBJECT ORIENTED PROGRAMMING (OOP) WITH JAVASCRIPT LECTURE OOP IN JAVASCRIPT OOP IN JAVASCRIPT: PROTOTYPES “CLASSICAL OOP”: CLASSES OOP IN JS: PROTOTYPES Class Prototype Instance ๐ Objects (instances) are instantiated from a class, which functions like a blueprint; Contains methods PROTOTYPAL INHERITANCE/ DELEGATION INSTANTIATION ๐ ๐ Example: Array Object Can access methods ๐ 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. Behavior (methods) is copied from class to all instances. Array.prototype is the prototype of all array objects we create in JavaScript Therefore, all arrays have access to the map method! 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?” 1 2 3 Constructor functions ๐ Technique to create objects from a function; ๐ This is how built-in objects like Arrays, Maps or Sets are actually implemented. 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). Object.create() ๐ The easiest and most straightforward way of linking an object to a prototype object. โ The 4 pillars of OOP are still valid! ๐ Abstraction ๐ Encapsulation ๐ Inheritance ๐ Polymorphism 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 [Person()] [Person.prototype] .constructor calcAge: function ๐ The new operator: 1 An empty object is created 2 this keyword in constructor function call PROTOTYPE CHAIN PROTOTYPAL INHERITANCE/ DELEGATION is set to the new object .__proto__ 3 The new object is linked (__proto__ property) to the constructor function’s Object [jonas] name: ‘Jonas’ Can’t find calcAge here! โ This is how it works with function constructors and ES6 classes birthYear: 1990 __proto__: Person.prototype prototype property 4 The new object is returned from the constructor function call Always points to an object’s prototype THE PROTOTYPE CHAIN null Constructor function [Object()] Prototype [Object.prototype] __proto__: null .__proto__ Constructor function [Person()] Built-in constructor function for objects. This is used when we write an object literal: {…} === new Object(…) Prototype [Person.prototype] Here it is! This is an OBJECT itself! Remember, every object in JavaScript has a prototype! Series of links between objects, linked through prototypes (Similar to the scope chain) __proto__: Object.prototype .__proto__ PROTOTYPE CHAIN Can’t find hasOwnProperty here! Object [jonas] __proto__: Person.prototype Can’t find hasOwnProperty here! SECTION OBJECT ORIENTED PROGRAMMING (OOP) WITH JAVASCRIPT LECTURE OBJECT.CREATE HOW OBJECT.CREATE WORKS CONSTRUCTOR FUNCTIONS Prototype [PersonProto] calcAge: function .__proto__ AUTOMATIC Object [steven] name: ‘Steven’ birthYear: 2002 __proto__: PersonProto OBJECT.CREATE SECTION OBJECT ORIENTED PROGRAMMING (OOP) WITH JAVASCRIPT LECTURE INHERITANCE BETWEEN "CLASSES": CONSTRUCTOR FUNCTIONS INHERITANCE BETWEEN “CLASSES” Parent “CLASS” 2 Constructor Function Prototype PERSON INHERITANCE BETWEEN “CLASSES” Child Constructor Function Prototype “CLASS” 1 STUDENT Object โ Using class terminology here to make it easier to understand. More specific type of person, ideal as child class 1 Constructor functions 2 ES6 Classes 3 Object.create() INHERITANCE BETWEEN “CLASSES” Constructor function Prototype [Person.prototype] [Person()] .__proto__ Constructor function [Student()] Prototype [Student.prototype] __proto__: Person.prototype .__proto__ Object [mike] __proto__: Student.prototype Create connection manually using Object.create() PROTOTYPE CHAIN INHERITANCE BETWEEN “CLASSES” Constructor function Prototype [Person.prototype] [Person()] Constructor function [Student()] ๐ GOOD ๐ BAD Object [mike] __proto__: Student.prototype INHERITANCE BETWEEN “CLASSES” Constructor function [Person()] Prototype [Person.prototype] Prototype [Object.prototype] __proto__: Object.prototype Here it is! .__proto__ Constructor function [Student()] null Prototype [Student.prototype] PROTOTYPE CHAIN __proto__: Person.prototype .__proto__ Can’t find calcAge here! 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 .__proto__ Prototype [StudentProto] __proto__: PersonProto .__proto__ Object [jay] __proto__: StudentProto Student inherits from Person PROTOTYPE CHAIN SECTION OBJECT ORIENTED PROGRAMMING (OOP) WITH JAVASCRIPT LECTURE 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 Parent class Inheritance between classes, automatically sets prototype Child class Instance property (available on created object) Redefining private field Public method Constructor method, called by new operator. Mandatory in regular class, might be omitted in a child class Referencing private field and method Private method (โ Might not yet work in your browser. “Fake” alternative: _ instead of #) Getter method ๐ 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 Setter method (use _ to set property with same name as method, and also add getter) Static method (available only on class. Can not access instance properties nor methods, only static ones) Creating new object with new operator MAPTY APP: OOP, GEOLOCATION, EXTERNAL LIBRARIES, AND MORE! SECTION MAPTY APP: OOP, GEOLOCATION, EXTERNAL LIBRARIES, AND MORE! LECTURE HOW TO PLAN A WEB PROJECT PROJECT PLANNING Description of the application’s functionality from the user’s perspective. All user stories put together describe the entire application. 1. USER STORIES WHAT we will build 2. FEATURES 3. FLOWCHART HOW we will build it 4. ARCHITECTURE DEVELOPMENT 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. ๐ Common format: As a [type of user], I want [an action] so that [a bene t] What? Who? Example: user, admin, etc. Why? 2 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 3 As a user, I want to see all my workouts at a glance, so I can easily track my progress over time 4 As a user, I want to also see my workouts on a map, so I can easily check where I work out the most 5 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 fi 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 2. FEATURES USER STORIES 1 Log my running workouts with location, distance, time, pace and steps/minute FEATURES ๐ Map where user clicks to add new workout (best way to get location coordinates) ๐ Geolocation to display map at current location (more user 2 Log my cycling workouts with location, distance, time, speed and elevation gain friendly) ๐ Form to input distance, time, pace, steps/minute ๐ Form to input distance, time, speed, elevation gain 3 See all my workouts at a glance ๐ Display all workouts in a list 4 5 See my workouts on a map See all my workouts when I leave the app and come back later ๐ 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 3. FLOWCHART FEATURES 1 1. Geolocation to display map at current location 2 2. Map where user clicks to add new workout 3 5 3. Form to input distance, time, pace, steps/minute 8 4. Form to input distance, time, speed, elevation gain 6 5. Display workouts in a list 9 6. Display workouts on the map 7 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 โ 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! Added later 4 4. ARCHITECTURE FOR NOW, LET’S JUST START CODING ๐ SECTION MAPTY APP: OOP, GEOLOCATION, EXTERNAL LIBRARIES, AND MORE! LECTURE 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 ASYNCHRONOUS JAVASCRIPT: PROMISES, ASYNC/AWAIT AND AJAX LECTURE ASYNCHRONOUS JAVASCRIPT, AJAX AND APIS SYNCHRONOUS CODE THREAD OF EXECUTION BLOCKING ๐ Most code is synchronous; SYNCHRONOUS ๐ Synchronous code is executed line by line; ๐ Each line of code waits for previous line to finish; ๐ Long-running operations block code execution. Part of execution context that actually executes the code in computer’s CPU ASYNCHRONOUS CODE Asynchronous THREAD OF EXECUTION “BACKGROUND” CALLBACK WILL RUN AFTER TIMER Timer running ๐ Example: Timer with callback Executed after all other code (More on this in the lecture on Event Loop) Callback does NOT automatically make code asynchronous! ๐ Asynchronous code is executed after a task that runs in the “background” finishes; ASYNCHRONOUS Coordinating behavior of a program over a period of time ๐ 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! ASYNCHRONOUS CODE Asynchronous THREAD OF EXECUTION “BACKGROUND” CALLBACK WILL RUN AFTER IMAGE LOADS Image loading ๐ Example: Asynchronous image loading with event and callback ๐ Other examples: Geolocation API or AJAX calls addEventListener does NOT automatically make code asynchronous! ASYNCHRONOUS Coordinating behavior of a program over a period of time (More on this in the lecture on Event Loop) ๐ 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! WHAT ARE AJAX CALLS? 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 web API Asking for some data ๐ต๐น ๐ซ๐ฎ ๐ฌ๐ญ REQUEST (GET / POST / etc.) (e.g. browser) WEB SERVER ๐ฉ๐ป ๐ CLIENT RESPONSE Sending data back ๐ต๐น ๐ซ๐ฎ ๐ฌ๐ญ WHAT IS AN API? AJAX 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; XML data format ๐ There are be many types of APIs in web development: DOM API Geolocation API Own Class API JSON data format Most popular API data format “Online” API Just “API” ๐ “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. or f I P A n a There is everything ๐ Weather data ๐ Data about countries ๐ Flights data ๐ Currency conversion data ๐ 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-response model or Client-server architecture REQUEST (e.g. browser) WEB SERVER ๐ฉ๐ป ๐ CLIENT RESPONSE WHAT HAPPENS WHEN WE ACCESS A WEB SERVER GET /rest/v2/alpha/PT HTTP/1.1 DNS Host: www.google.com DNS LOOKUP h ps://104.27.142.889:443 1 Accept-Language: en-US Request body (only when sending data to server, e.g. POST) <BODY> CLIENT (e.g. browser) 2 h ps://restcountries.eu/rest/v2/alpha/ HTTP RESPONSE HTTP/1.1 200 OK Domain name Resource 3 TCP/IP socket connection ๐ฉ๐ป (HTTP or HTTPS) HTTP request headers (many different possibilities) User-Agent: Mozilla/5.0 HTTP REQUEST Protocol Start line: HTTP method + request target + HTTP version 4 WEB SERVER ๐ Start line: HTTP version + status code + status message Date: Fri, 18 Jan 2021 Content-Type: text/html HTTP response headers (many different possibilities) Transfer-Encoding: chunked tt tt <BODY> Response body (most responses) SECTION ASYNCHRONOUS JAVASCRIPT: PROMISES, ASYNC/AWAIT AND AJAX LECTURE PROMISES AND THE FETCH API WHAT ARE PROMISES? E S I M O PR ๐ Promise: An object that is used as a placeholder for the future result of an asynchronous operation. Less formal ๐ Promise: A container for an asynchronously delivered value. Less formal ๐ Promise: A container for a future value. Example: Response from AJAX call ๐ 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 ๐ ๐ 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 Asynchronous task has nished Before the future value is available ASYNC TASK PENDING ๐ LOTTERY TICKET FULFILLED Success! The value is now available BUILD PROMISE SETTLED ๐ฎ ๐ฐ REJECTED An error happened ๐ We are able handle these different states in our code! fi E.g. Fetch API returns promise ๐ฉ CONSUME PROMISE When we already have a promise. E.g. promise returned from Fetch API SECTION ASYNCHRONOUS JAVASCRIPT: PROMISES, ASYNC/AWAIT AND AJAX LECTURE ASYNCHRONOUS BEHIND THE SCENES: THE EVENT LOOP REVIEW: JAVASCRIPT RUNTIME ๐ Concurrency model: How JavaScript handles multiple tasks happening at the same time. “Container” which includes all the pieces necessary to execute JavaScript code APIs provided to the engine “Heart” of the runtime Sends callbacks from queue to call stack Ready-to-be-executed callback functions (coming from events) Where object are stored in memory Where code is actually executed Only ONE thread of execution. No multitasking! HOW ASYNCHRONOUS JAVASCRIPT WORKS BEHIND THE SCENES Where asynchronous tasks run WEB APIs fetch() setTimeout() Loading image DOM() Execution context add() log() ... Fetching data Execution context Like callback queue, but for callbacks related to promises. Has priority over callback queue! addEventListener() el.src querySelector() fetch fetch() then() callback callback MICROTASKS QUEUE Loading image ๐ Global Execution context CALL STACK Decides when each callback is executed: orchestration ๐ค EVENT LOOP Some callback Another callback CALLBACK QUEUE How can asynchronous code be executed in a non-blocking way, if there is only one thread of execution in the engine? MODERN JAVASCRIPT DEVELOPMENT: MODULES AND TOOLING SECTION MODERN JAVASCRIPT DEVELOPMENT: MODULES AND TOOLING LECTURE AN OVERVIEW OF MODERN JAVASCRIPT DEVELOPMENT MODERN JAVASCRIPT DEVELOPMENT Join all modules into one file Convert modern JavaScript back to ES5 MODULE MODULE BUNDLING 3RD-PARTY PACKAGE BUILD PROCESS DEVELOPMENT 3rd party modules TRANSPILING/ POLYFILLING JAVASCRIPT BUNDLE PRODUCTION or Development tools ๐ Contains open-source packages to include 3rd-party NODE PACKAGE MANAGER 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.) Both repository and software SECTION MODERN JAVASCRIPT DEVELOPMENT: MODULES AND TOOLING LECTURE AN OVERVIEW OF MODULES IN JAVASCRIPT AN OVERVIEW OF MODULES ๐ Compose software: Modules are small building blocks E L U D O M ๐ Reusable piece of code that encapsulates implementation details; that we put together to build complex applications; W HY S? E L U D O M ๐ 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; ๐ Usually a standalone file, but it doesn’t have to be. ๐ 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. MODULE IMPORT (DEPENDENCY) Module code EXPORT (PUBLIC API) NATIVE JAVASCRIPT (ES6) MODULES S E L U D O M 6 ES ES6 MODULE SCRIPT Scoped to module Global ๐ Default mode Strict mode “Sloppy” mode ๐ Top-level this undefined window โ YES ๐ซ NO <script type="module"> <script> Asynchronous Synchronous ๐ Top-level variables Modules stored in files, exactly one module per file. ๐ Imports and exports ๐ HTML linking ๐ File downloading import and export syntax โ Need to happen at top-level Imports are hoisted! HOW ES6 MODULES ARE IMPORTED Live connection, NOT copies Parsing index.js ๐ index.js Live connection, NOT copies ๐ math.js IMPORTING MODULES BEFORE EXECUTION Asynchronous downloading math.js Asynchronous downloading dom.js Linking imports to math.js exports Linking imports to dom.js exports Execution math.js Execution dom.js ๐ 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 Execution index.js ๐ dom.js SECTION MODERN JAVASCRIPT DEVELOPMENT: MODULES AND TOOLING LECTURE REVIEW: WRITING CLEAN AND MODERN JAVASCRIPT REVIEW: MODERN AND CLEAN CODE READABLE CODE FUNCTIONS ๐ 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 ๐ Use DRY principle (refactor your code) ๐ Use ES6 classes ๐ Don’t pollute global namespace, encapsulate instead ๐ Encapsulate data and don’t mutate it from outside the class ๐ Don’t use var ๐ Implement method chaining ๐ Use strong type checks (=== and !==) ๐ Do not use arrow functions as methods (in regular objects) REVIEW: MODERN AND CLEAN CODE AVOID NESTED CODE ASYNCHRONOUS CODE ๐ 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) ๐ Use multiple if instead of if/else-if ๐ Handle errors and promise rejections ๐ Avoid for loops, use array methods instead ๐ Avoid callback-based asynchronous APIs SECTION MODERN JAVASCRIPT DEVELOPMENT: MODULES AND TOOLING LECTURE DECLARATIVE AND FUNCTIONAL JAVASCRIPT PRINCIPLES IMPERATIVE VS. DECLARATIVE CODE Two fundamentally different ways of writing code (paradigms) 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 ๐ Example: Step-by-step recipe of a cake the result ๐ The HOW (step-by-step instructions) gets abstracted away ๐ Example: Description of a cake FUNCTIONAL PROGRAMMING PRINCIPLES FUNCTIONAL PROGRAMMING ๐ Declarative programming paradigm ๐ Based on the idea of writing software by combining many pure functions, avoiding side effects and mutating data 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() ๐ 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: ๐ Try to avoid side effects in functions: this is of course not always possible! DECLARATIVE SYNTAX ๐ Use array and object destructuring ๐ Use the spread operator (...) ๐ Use the ternary (conditional) operator ๐ Use template literals FORKIFY APP: BUILDING A MODERN APPLICATION SECTION FORKIFY APP: BUILDING A MODERN APPLICATION LECTURE PROJECT OVERVIEW AND PLANNING PROJECT PLANNING โณ LATER 1. USER STORIES 2. FEATURES 3. FLOWCHART PLANNING STEP 4. ARCHITECTURE DEVELOPMENT STEP 1. USER STORIES ๐ 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 t] As a user, I want to search for recipes, so that I can find new ideas for meals 2 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 3 As a user, I want to bookmark recipes, so that I can review them later 4 As a user, I want to be able to create my own recipes, so that I have them all organized in the same app 5 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 fi 1 2. FEATURES USER STORIES 1 2 3 4 5 Search for recipes FEATURES ๐ Search functionality: input field to send request to API with searched keywords ๐ Display results with pagination ๐ Display recipe with cooking time, servings and ingredients ๐ 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 ๐ Store bookmark data in the browser using local storage ๐ On page load, read saved bookmarks from local storage and display 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 3. FLOWCHART (PART 1) FEATURES 1. Search functionality: API search request 2. Results with pagination 3. Display recipe 1 3 Other features later 2 SECTION FORKIFY APP: BUILDING A MODERN APPLICATION LECTURE THE MVC ARCHITECTURE WHY WORRY ABOUT ARCHITECTURE? The perfect architecture ๐ Like a house, software needs a structure: the way we organize our code ๐ We can create our own architecture (Mapty project) STRUCTURE ๐ 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. MAINTAINABILITY ๐ A project is never done! We need to be able to easily change it in the future EXPANDABILITY ๐ We also need to be able to easily add new features COMPONENTS OF ANY ARCHITECTURE BUSINESS LOGIC ๐ Code that solves the actual business problem; ๐ Directly related to what business does and what it needs; ๐ Example: sending messages, storing transactions, calculating taxes, … STATE HTTP LIBRARY ๐ Essentially stores ๐ Responsible for all the data about the application making and receiving AJAX requests ๐ Should be the “single source of truth” ๐ UI should be kept in ๐ Optional but almost always necessary in real-world apps APPLICATION LOGIC (ROUTER) ๐ Code that is only concerned about the implementation of application itself; ๐ Handles navigation and UI events sync with the state ๐ State libraries exist Keeping in sync PRESENTATION LOGIC (UI LAYER) ๐ Code that is concerned about the visible part of the application ๐ Essentially displays application state THE MODEL-VIEW-CONTROLLER (MVC) ARCHITECTURE 1 3 WEB 2 2 MODEL HTTP LIBRARY 5 USER 4 BUSINESS LOGIC STATE VIEW CONTROLLER 4 0 APPLICATION LOGIC ๐ Bridge between model and views (which don’t know about one another) ๐ Handles UI events and dispatches tasks to model and view PRESENTATION LOGIC Connected by function call and import Data flow MODEL, VIEW AND CONTROLLER IN FORKIFY (RECIPE DISPLAY ONLY) CONTROLLER MODEL TO REMOVE VIEW 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 Code that wants to react: SUBSCRIBER Code that knows when to react: PUBLISHER 2 3 1 A() B ≠ B A(X) C X 0 4 Subscribe to publisher by passing in the subscriber function ๐ controlRecipes will be passed into addHandlerRender when program starts ๐ addHandlerRender listens for events (addEventListener), and uses 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 ๐ค ๐ 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