Theory Lectures V2 PDF
Document Details
Uploaded by InfallibleVenus
Tags
Summary
These are lecture notes about JavaScript, covering topics such as data types, boolean logic, functions, and more. The lectures are part of a course on web development, and the notes include a table of contents, introductions, and lesson plans.
Full Transcript
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!...
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 V A S C R I P T J A JAVASCRIPT IS A HIGH-LEVEL, We can use different styles of programming Based on objects, for OBJECT-ORIENTED, MULTI-PARADIGM storing most kinds of data PROGRAMMING LANGUAGE. 🤯 Instruct computer to do things THE ROLE OF JAVASCRIPT IN WEB DEVELOPMENT CONTENT NOUNS means “paragraph” ADJECTIVES VERBS p.hide(); p {color: red} means “hide the means “the paragraph” paragraph text is red” PRESENTATION PROGRAMMING LANGUAGE: BUILDING WEB APPLICATIONS EXAMPLE OF DYNAMIC EFFECTS / WEB APPLICATION Display user info on hover Show spinner + loading Show spinner + loading data in the background 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 Back-end apps Dynamic effects and Web applications on web applications in the web servers browser 😍 THIS COURSE 100% based on JavaScript. They might go away, but JavaScript won’t! Native mobile Native desktop applications applications JAVASCRIPT RELEASES... (MORE ABOUT THIS LATER) Biggest update to the New updates to JS language EVER every single year... ES6/ ES7/ ES8/ ES9/ ES10/ ES11/... ES5 ES2015 ES2016 ES2017 ES2018 ES2019 ES2020 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 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. Value has type, NOT variable! fi fi 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 “Sarah has a driver’s license AND good vision” OR good vision” 👇 Possible values Inverts true/false value A A AND TRUE FALSE OR TRUE FALSE TRUE TRUE FALSE TRUE TRUE TRUE B 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: Age is less than 30 true TRUE TRUE 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 TRUE TRUE TRUE B 👉 !A AND B true true true 👉 A OR !B false FALSE TRUE FALSE false 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 🙏 2016 – ∞ 👉 Release of ES2016 / ES2017 / ES2018 / ES2019 / ES2020 / ES2021 / … / ES2089 😅 fi BACKWARDS COMPATIBILITY: DON’T BREAK THE WEB! 👍 Modern JavaScript Engine BACKWARDS 1997 COMPATIBLE 2020 👉 Old features are never removed; 👉 Not really new versions, just DON’T BREAK THE WEB! incremental updates (releases) 👉 Websites keep working forever! 👎 Modern JavaScript 😂 Engine NOT FORWARDS 2020 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 👉 Fully supported in all browsers (down to IE 9 from 2011); ES5 👉 Ready to be used today 👍 👉 ES6+: Well supported in all modern browsers; ES6/ES2015 ↓ 👉 No support in older browsers; ES2020 👉 Can use most features in production with transpiling and polyfilling 😃 👉 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 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; 👉 When working on old codebases, these will be written in ES5. fi 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 3 8 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 Parameters: placeholders to receive input Function body: block of code that values. Like local variables of a function we want to reuse. Processes the Function name 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 Arguments: actual values value (function output) 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 💥 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! HOW TO SUCCEED 🎉 AT LEARNING HOW TO CODE 💥 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! 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 👍 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 👍 Don’t be stuck in “tutorial hell” 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 could start applying to jobs 👍 Explain new concepts to other people. If you can explain it, FIX you truly understand it! 👍 The biggest misconception 👍 Share your goals to make that people have! yourself accountable 👍 Courses are an amazing 👍 Share your learning progress NEXT SLIDE starting point, but are only the with the web dev community beginning of your journey! (#100DaysOfCode, #CodeNewbie, #webdev, etc.) LEARNING HOW TO CODE IS HARD, BUT YOU CAN DO IT! Study courses: understand code, take challenges and notes 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 Keep challenging yourself, run into lots of problems, and fix them Round up your skillset with best Competence practices and tools (git, testing, …) You’re probably somewhere here 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 💥 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…) John can code now 😁 👍 Use my 4-step framework to solve any problem NEXT SLIDE fi 4 STEPS TO SOLVE ANY PROBLEM 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” 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 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 👉 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 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” 3 👉 How to check if a value is a number in JavaScript? Divide and conquer: Break a big 2 problem into smaller sub-problems. 👉 How to check if a value is a string in JavaScript? 👉 How to check if a value is an array in JavaScript? 👉 How to reverse a number in JavaScript? Don't be afraid to do as much 3 research as you have to 👉 How to reverse a string in JavaScript? 👉 How to reverse an array in JavaScript? 4 STEPS TO SOLVE ANY PROBLEM 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 if value type == string reverse string Don't be afraid to do as much 3 if value type == number research as you have to reverse number if value type == array reverse array For bigger problems, write pseudo-code 4 return reversed value before writing the actual code 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]) 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 👉 Debugging: Process of finding, fixing and preventing bugs. THE DEBUGGING PROCESS Isolating where Becoming aware Preventing it from exactly the bug is Correct the bug that there is a bug happening again happening in code IDENTIFY FIND FIX PREVENT 👉 During development 👉 Developer console 👉 Replace wrong 👉 Searching for the (simple code) solution with new same bug in similar 👉 Testing software correct solution code 👉 Debugger (complex 👉 User reports during code) 👉 Writing tests using production testing software 👉 Context: browsers, users, etc. 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 CAN INTERACT Fetch 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 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 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 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 Non-blocking event loop DECONSTRUCTING THE MONSTER DEFINITION High-level Garbage-collected Abstraction over 0s and 1s Interpreted or just-in-time compiled CONVERT TO MACHINE CODE = COMPILING Multi-paradigm Prototype-based object-oriented Happens inside the JavaScript engine First-class functions Dynamic Single-threaded More about this Later in this Section 👇 Non-blocking event loop 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 Interpreted or just-in-time compiled using so far 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 👉 Non-blocking event loop DECONSTRUCTING THE MONSTER DEFINITION High-level Prototype Array Garbage-collected Array.prototype.push (Oversimplification!) Interpreted or just-in-time compiled Array.prototype.indexOf 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 👉 Non-blocking event loop DECONSTRUCTING THE MONSTER DEFINITION High-level 👉 In a language with first-class functions, functions are simply treated as variables. We can pass them into other functions, and return them Garbage-collected 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 More about this in Section A Closer Look at Functions 👉 Non-blocking event loop DECONSTRUCTING THE MONSTER DEFINITION High-level 👉 Dynamically-typed language: Garbage-collected Interpreted or just-in-time compiled No data type definitions. Types becomes known at runtime Multi-paradigm Data type of variable is Prototype-based object-oriented automatically changed First-class functions Dynamic Single-threaded Non-blocking event loop DECONSTRUCTING THE MONSTER DEFINITION 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. So what about a long-running task? Multi-paradigm 👉 Sounds like it would block the single thread. However, we want non-blocking Prototype-based object-oriented behavior! (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 Non-blocking event loop More about this Later in this Section 👇 fi SECTION HOW JAVASCRIPT WORKS BEHIND THE SCENES 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 CALL STACK HEAP How is it Where our code Where objects compiled? is executed 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. STEP 1 STEP 2 Portable file: Program Source code machine code running COMPILATION EXECUTION Can happen way after compilation 👉 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 NOT a portable file Happens immediately 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 RUNTIME IN THE BROWSER Functionalities provided to Container including all the things the engine, accessible on that we need to use JavaScript ENGINE WEB APIs window object (in this case in the browser) DOM Timers Fetch API... EVENT LOOP Essential for non-blocking concurrency model CALLBACK QUEUE onClick click timer data... HEAP CALL STACK 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 click timer data... HEAP CALL STACK SECTION HOW JAVASCRIPT WORKS BEHIND THE SCENES LECTURE EXECUTION CONTEXTS AND THE CALL STACK WHAT IS AN EXECUTION CONTEXT? Compilation EXECUTION CONTEXT 👉 Human-readable code: Environment in which a piece of JavaScript is executed. Stores all the necessary Creation of global execution context (for top-level code) information for some code to be executed. “JavaScript code" NOT inside a function 📦 🍕 +🍴 + 🧾 EXECUTION Execution of top-level code Pizza “execution context” (inside global EC) 👉 Exactly one global execution context (EC): Default context, created for code that is not Function body inside any function (top-level). only executed Execution of functions and when called! waiting for callbacks 👉 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 Literally the name = ‘Jonas’ function code WHAT’S INSIDE EXECUTION CONTEXT? first = second = x = Variable Environment Need to run 1 first() first 👉 let, const and var declarations first() 👉 Functions 👉 arguments object a = 1 b = Need to run second() first 2 Scope chain NOT in arrow functions! 3 this keyword second() c = 2 arguments = [7, 9] Generated during “creation phase”, right before execution Array of passed arguments. Available (Technically, values in all “regular” functions (not arrow) 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 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: 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 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! 👉 Functions are also block scoped (only in strict mode) THE SCOPE CHAIN (Considering only variable declarations) Global scope Global variable myName = “Jonas” VARIABLE LOOKUP IN SCOPE CHAIN let and const are block-scoped SCOPE CHAIN first() scope Variables not in age = 30 current scope millennial = true var is function-scoped myName = “Jonas” Scope has access to variables from all outer scopes if block scope second() scope decade = 3 job = “teacher” age = 30 age = 30 millennial = true millennial = true myName = “Jonas” myName = “Jonas” SCOPE CHAIN VS. CALL STACK Global scope a = “Jonas” third() EC first = third = d = “Hey!” second() EC first() scope third() scope c = “Hi!” b = “Hello!” d = “Hey!” second = a = “Jonas” first() EC a = “Jonas” first = first = third = b = “Hello!” third = second = SCOPE CHAIN Global EC second() scope Order in which functions a = “Jonas” c = “Hi!” are written in the code first = third = b = “Hello!” second = CALL STACK a = “Jonas” ☝ Has nothing to do c and b can NOT be found first = with order in which Variable Order in which in third() scope! third = functions were called! environment (VE) 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 BEHIND THE SCENES ✅ 👉 Scope chain 👉 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 In strict mode. Otherwise: function! 👇 👇 👇 function declarations ✅ YES Actual function Block var variables ✅ YES undefined Function Technically, yes. But not in practice let and const variables 🚫 NO , TDZ Block function expressions and arrows 🤷 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 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 function is actually called. 👉 Method example: Method 👉 this = In strict mode! Otherwise: window (in the browser) Don’t get Simple function call 👉 this = undefined own this Arrow functions 👉 this = Event listener 👉 this = new, call, apply, bind 👉 calcAge jonas 1989 is method ☝ this does NOT point to the function itself, and also NOT the its variable environment! 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 ENGINE OBJECTS 👉 Number 👉 Object literal STORED IN 👉 String 👉 Arrays 👉 Boolean 👉 Functions STORED IN 👉 Undefined 👉 Many more… 👉 Null 👉 Symbol 👉 BigInt REFERENCE TYPES CALL STACK HEAP PRIMITIVE TYPES PRIMITIVE VS. REFERENCE VALUES 👉 Primitive values example: Identifier Address Value Address Value 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 CALL STACK HEAP “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) 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 ARRAYS VS. SETS AND OBJECTS VS. MAPS ARRAYS VS. SETS OBJECTS VS. MAPS 👉 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 👉 Use when you need to 👉 Use when you simply need include functions (methods) to map key to values 👉 Use when working with 👉 Use when you need keys JSON (can convert to map) 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 HIGHER-ORDER FUNCTIONS 👉 JavaScript treats functions as first-class citizens 👉 A function that receives another function as an 👉 This means that functions are simply values argument, that returns a new function, or both 👉 Functions are just another “type” of object 👉 This is only possible because of rst-class functions 👉 Store functions in variables or properties: 1 👉 Function that receives another function 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 👉 Call methods on functions: Returned function fi SECTION A CLOSER LOOK AT FUNCTIONS LECTURE CLOSURES “CREATING” A CLOSURE Global scope secureBooking = booker = Variable Environment secureBooking() scope passengerCount = 0 secureBooking() EC secureBooking = booker = passengerCount = 0 Global EC secureBooking = booker = CALL STACK Order in which Order in which functions SCOPE CHAIN functions were called are written in the code UNDERSTANDING CLOSURES secureBooking() EC Variable Environment of Execution Context in which passengerCount = 0 booker was created Global scope secureBooking = booker = secureBooking() scope passengerCount = 0 booker() EC secureBooking = booker = This is the function booker() scope Global EC secureBooking = secureBooking = booker = booker = 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 = booker = secureBooking() scope passengerCount = 0 (Priority over booker() EC scope chain) secureBooking = booker = CLOSURE This is the function booker() scope Global EC 2 1 passengerCount = 0 secureBooking = secureBooking = booker = booker = 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 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 4 3 2 3 1 4 3 2 MAP FILTER REDUCE Example Accumulator current * 2 current > 2 acc + current 1 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:.push (end).map (loop).indexOf.includes.reduce.unshift (start) (Boil down array to single 👉 Filtered using condition: 👉 Based on test condition: 👉 Based on test condition: value of any type: number, 👉 Remove from original:.filter.findIndex.some string, boolean, or even new array or object).pop (end).every 👉 Portion of original:.shift (start).slice.splice (any) An array element A new string To just loop array 👉 Adding original to other: 👉 Based on test condition: 👉 Based on separator string: 👉 Based on callback: 👉 Others:.concat.find.join.forEach.reverse 👉 Flattening the original:.sort (Does not create a new array,.flat just loops over it).fill.flatMap 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 “Types” of DOM objects DOM tree.querySelector() /.addEventListener() /.createElement() / (next slide).innerHTML /.textContent /.children / etc... HOW THE DOM API IS ORGANIZED BEHIND THE SCENES 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() Paragraph METHODS AND.querySelector() PROPERTIES.closest().matches() Element Text Comment Document.scrollIntoView() Example:.setAttribute() Paragraph.querySelector() Any HTMLElement will.createElement() have access to.getElementById().addEventListener(), HTMLElement.cloneNode() or.closest() methods. HTMLButtonElement... HTMLDivElement (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 1 3 CAPTURING BUBBLING PHASE PHASE (THIS DOES NOT HAPPEN 2 TARGET PHASE ON ALL EVENTS) SECTION ADVANCED DOM AND EVENTS LECTURE EFFICIENT SCRIPT LOADING: DEFER AND ASYNC DEFER AND ASYNC SCRIPT LOADING HEAD BODY END REGULAR Parsing HTML Waiting... Finish parsing HTML Parsing HTML Fetch script Execute Time Fetch script Execute DOMContentLoaded DOMContentLoaded ASYNC Parsing HTML Waiting Finish parsing HTML 👉 Makes no sense 🤷 Fetch script Execute DOMContentLoaded DEFER Parsing HTML Execute 👉 Makes no sense 🤷 Fetch script DOMContentLoaded REGULAR VS. ASYNC VS. DEFER END OF BODY ASYNC IN HEAD DEFER IN HEAD Parse HTML Fetch Run Parse HTML Wait Parse HTML Parse HTML Run DOMContentLoaded Fetch Run DOMContentLoaded Fetch DOMContentLoaded 👉 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) You can, of course, use different strategies for different scripts. Usually a Parse HTML Parse HTML complete web applications includes more than just one script Fetch Run Fetch Run 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 👉 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;