0% found this document useful (0 votes)
21 views

JS Class

Uploaded by

remidalpe5
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

JS Class

Uploaded by

remidalpe5
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

SEE MDN LINK LIST

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 Declarations => Can be used before it's declared


Function Expressions => function value stored in a variable
Arrow Function(ES6+) => one line function (no 'this' keyword) e.g.=> const functionName = parameters => 2037 - birthYear;
- Think about how you want to use this keyword when choosing a function
______________________________________________________________________________________________________
.push // Add at the end of an array
.unshift // Add at the start of an array
.pop // Removes last value of an array

.length // Number of values in an array


.indexof() // Return index of a value in an array
.includes() // Return true or false if the value is found in the array

Function within the .addEventListener('…', here); is called only when condition e.g. 'click' is fulfilled
______________________________________________________________________________________________________

- Bad practice to chain 'splice' or 'reverse' methods


- Callback functions (.forEach(function (acc, mov, i, arr)) needs to be: (accumulator, current element, current
index, entire array we loop over)

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)

- Document: entry point, using querySelector()


- Use = to set things on the DOM

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")

JS Behind The Scenes


JavaScript is a high-level, object-oriented, multi-paradigm programming language
-Or-
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.

High-Level: No need to manage resources manually (low: c / high: JS,PY)


Garbage-Collected: Cleans the memory
Interpreted or Just-In-Time Compiled: Convert to machine code = Compiling, inside the JS engine
Multi-Paradigm:
Paradigm: An approach and mindset of structuring code, which direct your coding style and technique.
1. Procedural programming (What we've been doing so far)
2. Object-oriented programming (OOP)
3. Functional programing (FP)
- Are either Imperative vs Declarative
- JavaScript Can do all 3
Prototype-Based Object-Oriented: Like for .push();, arrays are created from an array blueprint called "prototype", which contains all the arrays methods, the array created in code
then inherit the methods from the blueprints
first-class functions: Functions are treated as variables. We can pass them around into other functions, and return them from functions.
Dynamic: Or, dynamically-typed language: No need to assign data types to variables, they then only become known when JavaScript runs the code. The type of variables can be
changed when re-assigning variables.
Non-Blocking Event Loop:
Concurrency Model: How the JavaScript engine handles multiple tasks happening at the same time.
-Why we need that-
JavaScript runs in one single thread, so it can only do one thing at a time.
-What about long-running tasks?-
It would block the single thread. However, we want non-blocking behavior!
-How we achieve that?-
By using event loop: takes long running tasks, executes them in the "background", and puts them back in the main thread once they are finished.

Runtime In the Browser


- Container including all the things that we need to use JavaScript (in this case in the browser)
WEB APIs: Functionalities provided to the engine, accessible on window object (DOM, Timers, Fetch API, etc…)
Callback queue: Data structure of all the callback functions like; click, timer, data, etc…
- First thing to happen after the event is that the callback function is put in the callback queue, then when the call stack isempty the callback function is passed into the stack
to be executed by the event loop (event loop: essential for non-blocking concurrency model).
JavaScript Engine

Runtime In NODE.JS

Programing Journey Page 1


Runtime In NODE.JS
- No WEB APIS, we use C++ bindings & thread pool
Callback queue
JavaScript Engine

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

CODE e.g.: Global:


const name = 'Remi'; Name = 'Jonas'
const first = () => { First = <function> Literally the function code
let a = 1; Second = <function> (Technically, values
const b = second(7, 9); X = <unknown> Needs to run first() first only become known
a += b; during execution)
return a; first():
}; a =1
function second(x, y) {
b = <unknown> Needs to run second() first
var c = 2;
return c;
} second():
const x = first(); c=2
arguments = [7, 9] Array of passed arguments, available in all "regular" functions (not arrow)

JS Engine JS Engine JS Engine JS Engine JS Engine JS Engine


#3 EC: #3 EC: #3 EC: second() => return c; => #3 EC: #3 EC: #3 EC:
#2 EC: #2 EC: first() #2 EC: first() #2 EC: first() => first() is back to active EC / return a; => #2 EC: #2 EC:
#1 EC: Global #1 EC: Global #1 EC: Global #1 EC: Global #1 EC: Global => when execution is complete => #1 EC:
all tack all tack all tack all tack all tack all tack

Scoping & Scope in JavaScript


Concepts:
Scoping: How the 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

global scope function scope block scope (ES6)

const me = 'Remi'; function calcAge (birthyear) { if () {}, for () {}, etc...


const job = 'Student'; const now = 2037;
const year = 1989; const age = now - birthyear; - Variables are accessible only
return age; inside block (block scoped).
- Outside of any function or block. } - However, this only applies to
- Variables declared in global console.log(now);
let and const variables! A var
scope are accessible everywhere. can be scoped to current &
- Variables are accessible only
global scope.
inside function, NOT outside.
- Functions are also block
- Also called local scope.
scoped (only in strict mode).

Global scope (Considering only


SCOPE CHAIN variable declarations)
myName = 'Remi'
Scope has access
const myName = 'Remi';
first() scope to variables from
function first() {
const age = 30; all outer scopes
if (age >= 30) { age = 30
const decade = 3; millennial = true
var millennial = true;
} myName = 'Remi'
function second() {
const job = 'student';
console.log(`${myName} is a ${age}-old ${job}`)
} Second() scope If block scope
second();
}
job = 'student' decade = 3
first();
Age = 30 Age = 30
Millennial = true
myName = 'Remi'
myName = 'Remi'

Variable lookup in scope chain

Scope chain vs. Call stack JS Engine Scope chain

const a = 'Remi'; third() EC: Global scope VE:


first(); d = 'Hey!' a = 'Remi' Scope chain has
second() EC: first = <function> nothing to do with
function first() { c = 'Hi!' third = <function> the order in which

Programing Journey Page 2


Scope chain vs. Call stack JS Engine Scope chain

const a = 'Remi'; third() EC: Global scope VE:


first(); d = 'Hey!' a = 'Remi' Scope chain has
second() EC: first = <function> nothing to do with
function first() { c = 'Hi!' third = <function> the order in which
const b = 'Hello!'; first() scope VE: functions were
second(); first() EC: called!
b = 'Hello!' b = 'Hello!'
function second() {
const c = 'Hi!'; second = <function> second = <function>
third(); ---------------
Global EC: a = 'Remi'
}
} a = 'Remi' first = <function>
first = <function> third = <function>
function third() { third = <function>
second() scope VE:
const d = 'Hey!'; all tack
console.log(d + c + b + a);
c = 'Hi!'
// Reference Error ---------------
} b = 'Hello!'
second = <function>
---------------
a = 'Remi'
first = <function>
third = <function>
third() scope VE:
d = 'Hey!'
---------------
c = 'Hi!'
---------------
b = 'Hello!'
second = <function>
---------------
a = 'Remi'
first = <function>
third = <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.

Hoisted? Initial value Scope


Function declarations Yes Actual function Block => In strict mode, otherwise: function
var variables Yes Undefined function
Let and const variables No (yes, but not in practice) <uninitialized>, TDZ* Block
Function expression and arrows Depends if using var or let/const // //
* Temporal Dead Zone

Temporal dead zone, let & const


const myName = 'Remi';

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

How the this keyword works


- this keyword/variable: Special variable that is created for every execution context (every function). Takes the value of (points to) the
"owner" of the function in which the this keyword is used.
- this is NOT static, it depends on how the function is called, and its value is only assigned when the function is actually called.

Method - this = <Object that is calling the method>


e.g.
calcAge is a method
const remi = {
name: 'Remi', this = remi, year = 2004
year: 2004,
calcAge: function() { Way better than using remi.year
return 2024 - this.year;
}
};
remi.calcAge();
Simple function call - this = undefined (In strict mode, otherwise: window in the browser)
Arrow functions - this = <this of surrounding function (lexical this)> (arrow function don’t get a this keyword)
Event listener - this = <DOM element that the handle is attached to>
new, call, apply, bind - <Later in the course>
this does NOT point to the function itself, and also NOT the its variable environment

Programing Journey Page 3


Review: Primitive, objects & the JS engine

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}

Data Structures, Modern Operators & Strings


Spread operator… & Rest pattern
Spread
○ … operator before an array returns all elements of an array (e.g. …arr)
○ Only usable in places we would otherwise write values separated by commas
○ For building new arrays, or pass multiple values into a function
Rest
○ Used when we would otherwise write variable names separated by commas
○ Cannot be used for values separated by commas

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

Simple List? Key/Value Pairs


Arrays or Sets Objects or Maps
Arrays Sets* Objects Maps
For ordered lists of values When we need unique values More 'traditional' key/value store Better performances
(can have duplicates)
For manipulating data When high-performance is really Easier to write & access values Keys can have any data type
important w/ . and [ ]
For removing duplicates from Easy to iterate
arrays
*deleting or searching for items Easy to compute size
can be 10x faster in sets vs arrays

- e.g. JSON data format:


{
// Object containing Array containing Object
"count": 3,
"examples": [
// Array within Object containing Object
{
// Object within Array
"property": "whatever"
},
{
// Object within Array
"property": "whatever"
}
]
}
- Other built-in:
○ WeakMap
○ WeakSet
- Non-built in:
○ Stacks
○ Queues
○ Linked Lists
○ Trees
○ Hash Tables

A Closer Look at Functions


First class functions:
- JS treats functions as first-class citizens
- Functions are simply values

Programing Journey Page 4


- Functions are simply values
- Function are just another "type" of object

Store functions in variables or properties:


const add = (a, b) => a + b;
const counter = {
value: 23,
inc: function () { this.value++; },
};

Pass functions as arguments to OTHER functions:


const greet = () => console.log('Hey Remi');
btnClose.addeventListener('click', greet);

Return functions FROM functions


Call methods on functions:
CountQueuingStrategy.inc.bind(someOtherObject);

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 that receives another function:


const greet = () => console.log('Hey Remi');
btnClose.addEventListener('click', greet);
Higher-order function Call back function

Function that returns new function:


function count () { // Higher-order function
let counter = 0;
return function () { // Returned function
counter++;
}
}

Why JS always uses callbacks


- Callback functions allows abstraction
- Makes easier to split the code into more usable parts

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.

Programing Journey Page 5


- Reduce: boils/reduces all array elements down to one single value


○ e.g. Accumulator

Which Array Method to Use?

DOM nodes

Defer & Async script loading

Programing Journey Page 6


OOP const user = {
- OOP is a programming paradigm based on the concept of objects user: 'remi',
- We use objects to model (describe) real-world or abstract (html, data structure, …) features password: '12345', Data
- Objects may contain data (properties) and code (methods). By using objects, we pack data and
the corresponding behavior into one block login (password) {
- In OOP, objects are self-contained pieces/block of code // Login logic
- Objects are building blocks of applications and interact with one another },
sendMessage (str) { Behaviour
- Interactions happen through a public interface (API): methods that the code outside of the object
// Send msg logic
can access and use to communicate with the object
}
- OOP was developed with the goal of organizing code, to make it more flexible and easier to }
maintain (avoid "Spagetti Code")
Class

Programing Journey Page 7

You might also like