JS Class
JS Class
JS Class
September 4, 2024 2:25 AM
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#options
const > let(only if sure value is needed to change) > var(avoid) - Intl.NumberFormat() constructor
- Call variables only at top of each scopes for best practices https://developer.mozilla.org/en-US/docs/Web/API/Node
- Also, always declare functions first and use them after declaration for best practice - DOM nodes
https://developer.mozilla.org/en-US/docs/Web/Events
______________________________________________________________________________________________________ - Event references
function functionName(parameters) {
// Function Body //
// Block of code to reuse //
const arguments = parameters; // Parameters are Arguments
return value; // Output a value & terminate execution, needed when more than one line of code
}
const variable = functionName(arguments); // Calling / running / invoking using ()
Function within the .addEventListener('…', here); is called only when condition e.g. 'click' is fulfilled
______________________________________________________________________________________________________
DOM
DOCUMENT OBJECT MODEL: structured representation of html documents. Allows JavaScript to access HTML elements and styles to
manipulate them. NOT A PART OF JS & VICE VERSA, DOM IS PART OF BROWSER API (WHICH WE CAN INTERACT W/ JS)
e.g.
Document => Element(<HTML>) => Element(<HEAD>) => Element(<title>) => Text("A simple page")
=> Element(<BODY>) => Element(<section>) => Element(<img>)
=> Element(<section>) => Element(<p>) => Text("A second paragraph")
=> Element(<p>) => Text("A paragraph")
=> Element(<a>) => Text("link")
Runtime In NODE.JS
JS Engine
- Program that executes JavaScript code
HEAP: Where objects are stored
ALL TA here code is e ecuted, where e ecu on conte ts get stacked on top of each other to keep track of where we are in the e ecu on
Compilation vs Interpretation
Compilation: Entire code is converted into machine code at once, and written to a binary file that can be executed by a computer.
[Source code] Compilation => [Portable file: machine code] Execution => [Program running]
Can happen way after compilation
Interpretation: Interpreter runs through the source code and executes it line by line.
[Source code] Execution line by line => [Program running]
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
[Source code] Compilation => [Machine code] Execution => [Program running]
NOT a portable file Happens immediately
Step.1: Parsing (reading the code) through AST
Step.2: Takes AST & compiles it to machine code. (JIT)
Step.3: Execution (happens in call stack)
Step.4: Optimization during execution
JS engine makes the fastest but unoptimized machine code to start executing ASAP, then code is optimized & recompiled during the already running program execution
Execution Context
- Environment in which a piece of JavaScript is executed. Stores all the necessary information for some code to be executed.
- What's inside: (generated at "creation phase", right before execution)
○ Variable Environment: let, const & var declarations / functions / arguments (not in arrow function) object
○ Scope chain
○ this keyword (not in arrow function)
Exactly one global execution context (EC): Default context, created for code that is not inside any function (top-level).
One execution context per function: For each function call, new execution context is created.
Execution
[Compilation] => [Creation of global execution context (for top-level code)] => [Execution of top-level code (inside global EC)] => [Execution of functions and waiting for callbacks]
NOT inside a function
Summary
- Scoping asks the question "Where do variables live?" or "Where can we access a certain variable,
and where not?"
- There is 3 types of scope in JS: global scope, scopes defined by functions, and defined by blocks
- Only let and const variables are block-scoped. Variables declared with var end up in the closest
function scope
- In JS, there is 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 cope chain in a certain scope is equal to adding together all the variable environments of all
the parent scopes
- The scop chain has nothing to do with the order in which functions were called. It does not affect
the scope chain at all!
Hoisting in JavaScript
- Hoisting makes some types of variables accessible/usable in the code before they are actually declared. "Variables lifted to the top of their
scope"
-Behind the scenes-
- Before execution, code is scanned for variable declarations, and for each variable, a new property is created in the variable environment
object.
if (myName === 'Remi') { Temporal dead zone for job variable called with let/const
console.log(`${myName} is a ${job}`);
const age = 2024 - 2004; Why TDZ?
console.log(age); - Makes it easier to avoid and catch
const job = 'teacher';
errors: accessing variables before
console.log(x);
} declaration is bad practice and should
be avoided
- Makes const variables actually work
Why hoisting
- Using functions before actual declaration
- var hoisting is just a byproduct
Primitives
Objects
Number JS engine Object literal
String -------- ....... Arrays
Boolean Call stack Heap Functions
Undefined
Many more…
Null
Reference types
Symbol
BigInt
Primitive types
JS engine
- Primitive values example
let age = 20;
let oldAge = age;
age = 31; Identifier Address Value D30F {
console.log(age);// 31 name:'Remi';
console.log(oldAge);// 20 age 0001 30 age: 20 27;
- Reference values example: }
oldAge 0002 31
const me = {
name: 'remi', me 0003 D30F
age: 20, Heap
friend
};
const friend = me; Call stack
friend.age = 27;
console.log('Friend:', friend);
// { name: 'Remi', age: 27}
console.log('me', me);
// { name: 'Remi', age: 27}
Short circuiting (&& and ||) & The Nullish Coalescing Operator (??)
- Short-circuiting is a behavior exhibited by logical operators where the elevation of the second operand is skipped if the outcome c an be
determined by evaluating the first operand alone.
○ || operator returns the first truthy operand, or the last falsy operand if all operands are falsy.
○ && operator returns the first falsy operand, or the last truthy operand if all operands are truthy.
- The nullish coalescing operator (??) is a logical operator that returns its right -hand side operand when its left-hand side operand is null
or undefined, and otherwise returns its left-hand side operand
Sets
- sets are collections of values, which are unique
Maps
- map objects are collections of key-value pairs, keys are unique
Data Structures
Sources of Data
1. From the program itself: Data written directly in source code (e.g. status message)
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)
Collection Data
Data Structure
Higher-order functions:
- Function that receives another function as an argument, that returns a new function, or both
- Only possible because of first-class functions
Function methods
- .call()
○ call() method of f instance calls this function with a given this value & provides arguments individually
○ e.g. greet.call(person) this = person & this != greet
- .bind()
○ bind() method of f instance creates new function, which is called with this keyword set to provided value
○ Useful for functions returning functions using this keyword
- .apply()
○ apply() method of f instance calls this function
!!!Closures!!!
Call Stack (function call order) Scope Chain (function write order)
const secureBooking = function () { Global EC: Global scope:
let passengerCount = 0; secureBooking = <f> secureBooking = <f>
return function () {
booker = <f> booker = <f>
passengerCount++;
console.log(`${passengerCount} passengers`); secureBooking() EC: secureBooking() scope:
}; passengerCount = 0 passengerCount = 0
}; (popped out after execution ) -----------------------------------
const booker = secureBooking(); --- When booker is called --- secureBooking = <f>
booker(); Booker() EC: booker = <f>
Closure
booker(); passengerCount = 0 <empty>
booker(); Booker() scope:
<empty>
-----------------------------------
secureBooking() = <f>
Booker = <f>
- Closures makes a function remember all the values once stored at the function birthplace
○ Function has access to the 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
○ Closure has priority over scope chain
Summary
- 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 lose connection to variables that existed at the function's birth place.
- Less formal -
- A closure is like a backpack that a function carries around wherever it goes. This backpack has all the variables that were present in the environment
where the function was created.
○ We do NOT have to manually create closures, this is a JavaScript feature that happens automatically. We can't even access closed -over
variables explicitly. A closure is NOT a tangible JavaScript object.
Bankist Section
Data Transformations: map, filter, reduce:
- Map: returns a new array containing the results of applying an operation on all original array elements
○ e.g.
- Filter: returns a new array containing the array elements that passed a specified test condition
○ e.g.
DOM nodes