Javascript in the Browser: DOM and Events Fundamentals PDF

Document Details

PraisingEinstein

Uploaded by PraisingEinstein

Tags

javascript dom manipulation programming web development

Summary

This document provides an overview of Javascript in the browser focusing on DOM and DOM manipulation. It also covers Javascript concepts such as the event loop, execution contexts, and the call stack. A review of primitives, objects, and the Javascript engine is included in the text.

Full Transcript

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

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