Js Engine Flashcards
ReferenceError vs. TypeError
ReferenceError: is scope resolution-failure related.
The ReferenceError object represents an error when a variable that doesn’t exist (or hasn’t yet been initialized) in the current scope is referenced.
TypeError: If a variable is found (successful scope resolution), but you try to do something impossible with its value, for example, you tried to execute the variable as a function, but it is a number, then TypeError will be called by Engine.
Namespace
JavaScript namespace is a concept of adding classes, methods, variables, and objects inside a container. It is a programming paradigm that is utilized for assigning scope to the identifiers, such as variables and functions name. Javascript namespace assists in preventing the collision between the same name variables and functions.
Expression
An expression is a valid unit of code that resolves to a value.
Statement
A statement is an instruction to perform a specific action. Such actions include creating a variable or a function, looping through an array of elements, evaluating code based on a specific condition etc. JavaScript programs are actually a sequence of statements.
node-fetch
minimal code for a window.fetch compatible API on Node.js runtime.
polyfill
A polyfill is a piece of code (usually JavaScript on the Web) used to provide modern functionality on older browsers that do not natively support it.
The Jest Object
The jest object is automatically in scope within every test file (not applicable to typescript?). The methods in the jest object help create mocks and let you control Jest’s overall behavior. It can also be imported explicitly by via import {jest} from ‘@jest/globals’.
INFO
The TypeScript examples from this page will only work as documented if you explicitly import Jest APIs:
import {expect, jest, test} from ‘@jest/globals’;
TypeScript Casting
Casting is the process of overriding a type.
Casting doesn’t actually change the type of the data within the variable.
[Using the ‘as’ keyword ]
let x: unknown = ‘hello’;
console.log((x as string).length);
[Using the ‘<>’(will not work with TSX)]
let x: unknown = ‘hello’;
console.log((<string>x).length);</string>
https://instil.co/blog/typescript-testing-tips-mocking-functions-with-jest/
https://stackoverflow.com/questions/54165536/typescript-function-return-type-based-on-input-parameter
https://dev.to/ruizb/function-purity-and-referential-transparency-7h1
the constructor() method
The constructor method is a special method of a class for creating and initializing an object instance of that class.
The super keyword
The super keyword is used to:
- Access properties on an object literal or class’s [[Prototype]];
- Invoke a superclass’s constructor.
In the constructor body of a derived class (with extends), the super keyword may appear as a “function call” (super(…args)), which must be called before the this keyword is used, and before the constructor returns. It calls the parent class’s constructor and binds the parent class’s public fields, after which the derived class’s constructor can further access and modify this.
Function.prototype.bind()
bind is a method on the prototype of all functions in JavaScript. It allows you to:
**Create a new function from an existing function, change the new function’s this context,
and provide any arguments you want the new function to be called with. The arguments provided to bind will precede any arguments that are passed to the new function when it is called. No
the static keyword of a class
The static keyword defines a static method or property for a class, or a static initialization block.
Neither static methods nor static properties can be called on instances of the class. Instead, they’re called on the class itself.
Static methods are often utility functions, such as functions to create or clone objects, whereas static properties are useful for caches, fixed-configuration, or any other data you don’t need to be replicated across instances.
HTTP
Hypertext Transfer Protocol (HTTP) is an application-layer protocol for transmitting hypermedia documents, such as HTML.
- It was designed for communication between web browsers and web servers, but it can also be used for other purposes.
-HTTP follows a classical client-server model, with a client opening a connection to make a request, then waiting until it receives a response. - HTTP is a stateless protocol, meaning that the server does not keep any data (state) between two requests.
REST
REST is a software architectural style
REST is not a protocol, but a set of architectural constraints.
(For a web service to be truly RESTful, it must adhere to the following constraints: )
- Stateless. Web servers don’t keep track of previous communication. Every client request must contain the details needed to complete itself effectively.
**No client context shall be stored on the server between requests. The client is responsible for managing the state of the application.
- Layered system. Client calls and server responses pass through several intermediary layers.
**REST allows you to use a layered system architecture where you deploy the APIs on server A, and store data on server B and authenticate requests in Server C, for example. A client cannot ordinarily tell whether it is connected directly to the end server or an intermediary along the way. - Client-Server. REST imposes the client-server design pattern to enforce the separation of concerns. The client app should only know the requested resource’s URI (Uniform Resource Identifier). The server application should only return the appropriate response and be unconcerned about the frontend UI.
**This constraint essentially means that client applications and server applications MUST be able to evolve separately without any dependency on each other. A client should know only resource URIs, and that’s all. Today, this is standard practice in web development, so nothing fancy is required from your side. Keep it simple. - Cacheable. Clients (and intermediaries) must be able to cache resources. Every response should define itself as cacheable or non-cacheable.
- Uniform interface. There are several guiding principles: individual resources are identified in requests using URIs as identifiers, clients can manipulate resources through representations, messages should be self-descriptive (include enough information about how to process them), and HATEOAS.
**A resource in the system should have only one logical URI, and that should provide a way to fetch related or additional data. It’s always better to synonymize a resource with a web page. - Code on demand (optional). Servers can temporarily extend or customize the functionality of a client by transferring executable code.
usly.
When to use REST
REST is ideal for:
Applications that need to perform actions on resources (e.g. retrieve, update) on an occasional, ad-hoc basis.
Request-driven, non-realtime, and stateless systems.
CRUD operations.
Cloud apps, microservices, and web apps.
https://restfulapi.net/rest-architectural-constraints/#layered-system
CRUD
create, read, update, and delete (CRUD) are the four basic operations of persistent storage.
WebSocket
WebSocket is a realtime protocol that enables full-duplex, bidirectional communication between a web client and a web server over a persistent, single-socket connection.
Similar to HTTP, WebSocket works on top of TCP. Unlike HTTP, WebSockets are stateful. They’re suitable for event-driven apps and services that require high-frequency, low-latency communication between client and server. Use cases include live chat, realtime dashboards, streaming live score updates, multi-user document collaboration, multiplayer gaming, and many more.
We can broadly group WebSockets use cases into two distinct categories:
- Realtime updates, where the communication is unidirectional, and the server is streaming low-latency (and often frequent) updates to the client. Think of live score updates or alerts and notifications, to name just a few use cases.
- Bidirectional communication, where both the client and the server send and receive messages. Examples include chat, virtual events, and virtual classrooms (the last two usually involve features like live polls, quizzes, and Q&As). WebSockets can also be used to underpin multi-user synchronized collaboration functionality, such as multiple people editing the same document simultaneously.
https://ably.com/topic/websocket-vs-rest#:~:text=WebSockets%20have%20a%20low%20overhead,%2C%20delete%2C%20or%20update%20resources.
Transmission Control Protocol (TCP)
TCP stands for Transmission Control Protocol.
It is a transport layer protocol that facilitates the transmission of packets from source to destination. I
t is a connection-oriented protocol that means it establishes the connection prior to the communication that occurs between the computing devices in a network.
This protocol is used with an IP protocol, so together, they are referred to as a TCP/IP.
https://www.khanacademy.org/computing/computers-and-internet/xcae6f4a7ff015e7d:the-internet/xcae6f4a7ff015e7d:transporting-packets/a/transmission-control-protocol–tcp
https://www.geeksforgeeks.org/what-is-transmission-control-protocol-tcp/
Referencial transparency
Referential transparency is the ability to replace an expression with its result, without changing the meaning/behavior of the program.
For functions, we can represent this property as a mapping between the “function reference + its inputs” and “its output”.
We can use the referential transparency property for optimization purposes (both developers and compilers), such as using lazy evaluation, memoization, or parallelization.
Function purity
A function is considered pure if it does not have any side effects.
In other words, given some input, a function will always return the same output.
Node.js fs.readFile() Method
The fs.readFile() method is an Node.js inbuilt method which is used to read the file. This method read the entire file into buffer. To load the fs module we use require() method. For example: var fs = require(‘fs’);
- The simplest way to read a file in Node.js is to use the fs.readFile() method, passing it the file path, encoding and a callback function that will be called with the file data (and the error):
const fs = require(‘fs’);
fs.readFile(‘/Users/joe/test.txt’, ‘utf8’, (err, data) => {
if (err) {
console.error(err);
return;
}
console.log(data);
});
- The promise-based fsPromises.readFile() method offered by the fs/promises module:
const fs = require(‘fs/promises’);
async function example() {
try {
const data = await fs.readFile(‘/Users/joe/test.txt’, { encoding: ‘utf8’ });
console.log(data);
} catch (err) {
console.log(err);
}
}
example();
- the synchronous version fs.readFileSync():
…
https://nodejs.dev/en/learn/reading-files-with-nodejs/
require
Node.js follows the CommonJS module system, and the builtin require function is the easiest way to include modules that exist in separate files. The basic functionality of require is that:
** It reads a JavaScript file, executes the file, and then proceeds to return the exports object.
The rules of where require finds the files:
- If the file doesn’t start with “./” or “/”, then it is either considered a core module (and the local Node.js path is checked), or a dependency in the local node_modules folder.
- If the file starts with “./” it is considered a relative file to the file that called require.
If the file starts with “/”, it is considered an absolute path.
Extra note: if the filename passed to require is actually a directory, it will first look for package.json in the directory and load the file referenced in the main property. Otherwise, it will look for an index.js.
TypeScript async await
Modern JavaScript added a way to handle callbacks in an
// elegant way by adding a Promise based API which has special
// syntax that lets you treat asynchronous code as though it
// acts synchronously.
// Like all language features, this is a trade-off in
// complexity: making a function async means your return
// values are wrapped in Promises. What used to return a
// string, now returns a Promise<string>.</string>
What happens when you type a URL into your browser?
- You type a URL in your browser and press Enter
** https:// is the scheme. HTTPS stands for Hypertext Transfer Protocol Secure. This scheme tells the browser to make a connection to the server using Transport Layer Security, or TLS. TLS is an encryption protocol to secure communications over the Internet. - Browser looks up IP address for the domain??
** does this by looking up the domain, jennapederson.dev, to find the address. - Browser initiates TCP connection with the server
4.Browser sends the HTTP request to the server
- Server processes request and sends back a response
- Browser renders the content
DNS
Domain name system
V8 (JavaScript engine)
V8 is a JavaScript engine developed by the Chromium Project for Google Chrome.
It has also been used on the server side, for example in Couchbase and Node.js.
V8 compiles ECMAScript directly to native machine code using just-in-time compilation before executing it.
Call Stack
call stack is a data structure which records where in the program we are.
If we step into a function, we put something on to the stack, if we return from a function, we pop off the top of the stack
heap
memory allocation
AJAX
AJAX is a technique for accessing web servers from a web page.
AJAX stands for Asynchronous JavaScript And XML.
setTimeout
setTimeout is not a guaranteed time to execution, it’s a minimum time to execution,
just like setTimeout zero doesn’t run the code immediately it runs the code next‑ish
Instant HTML Boilerplate in VSCode With Emmet
- Create an empty index.html document.
- Place the cursor inside the html editor content and type ‘ ! ‘
parseInt()
console.log(parseInt(‘11’)) // => 11
Debounce vs. Throttle
- Debounce needs to wait for a delay between inputs in order to trigger - Debouncing works by delaying our function call by a set period of time. If nothing happens during that time then the function will run just like normal, but if something happens that causes the function to be called again during the delay then the delay will be restarted. (eg. autocomplete text boxes)
throttling
Debouncing and throttling are techniques that allow us to skip function execution if that function is called too many times over a certain time period.
- Throttle will call the function passed to it every time the delay ends as long as the trigger for the function is still happening. Throttle is ideal when you want to group multiple events into one event on a periodic basis.
Every time the delay ends you will get updated information on the event. (eg. resizing elements, drag and drop, scrolling, or other events that occur many times and you want to get updated on their values periodically )
Shortcut for adding a div with a class name
.<name></name>
1fr
1 fraction
1rem
rem stands for root em
- the em unit means “my parent element’s font-size”
- the rem unit means “The root element’s font-size”
Use rem
for Global Sizing; Use em
for Local Sizing
.grid {
width: 100%;
display: grid;
gap: 1rem; //same size of root element’s font-size
grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
grid-auto-rows: 200px; //specifies the size of an implicitly-created grid row track or pattern of tracks
}
.box {
min-width: 100px;
width: 75%;
max-width: 500px;
}
//shorthand version
.box{
width: clamp(100px, 75%, 500px)
font-size: clamp(0.75rem, 1.5vm, 2rem);
}
clamp can also used for font-size
DNS lookup
Domain Name System
race condition, dead lock
neural network
MapReduce or Hadoop
hired.com; triplebyte?? assessment?
https://resumeworded.com
Use T3 instead of Create React App
Runtime vs. Compile Time
Compile time is the period when the source code written using high-level language is converted to browser-executable code;
Runtime is the period of time when a program is running and generally occurs after compile time.
Netlify/AWS Lambda serverless functions
Mongoose
Mongoose is a MongoDB object modeling tool designed to work in an asynchronous environment. Mongoose supports Node.js and Deno (alpha)
Prima
Next-generation Node.js and TypeScript ORM(Object–relational mapping)
WebSocket handshake
The handshake starts with an HTTP request/response, allowing servers to handle HTTP connections as well as WebSocket connections on the same port. Once the connection is established, communication switches to a bidirectional binary protocol which does not conform to the HTTP protocol.
Action verbs
Harness, fine-tune
Git
Git is a distributed version control system
In software development, distributed version control (also known as distributed revision control) is a form of version control in which the complete codebase, including its full history, is mirrored on every developer’s computer.[
regular expression
A regular expression (shortened as regex or regexp) is a sequence of characters that specifies a search pattern in text.
Usually such patterns are used by string-searching algorithms for “find” or “find and replace” operations on strings,
or for input validation.
API
An API or Application Programming Interface is a messenger or a middleman that lets computer programs securely access data from one another.
The API works as follows:
- The client places a request from their device, using the
HTTP GET, PUT, POST, or DELETE methods.
The request is sent via HTTP to the URI (Uniform Resource Identifier). The requests include the request method, headers, and body—for example, in XML, JSON, or other formats. - If the request is not valid, the API will not call the program but return an error.If the request is valid, the API makes a call to the required service.
- Once the API receives the response from the service, it sends the response back to the requesting application (client) via HTTP.
GraphQL
GraphQL (Graph Query Language) is a fast, stable, and flexible query language and runtime.
With GraphQL, developers can construct requests to pull the necessary data from multiple sources in a single call. The response contains only what is required.
Vercel
Vercel Inc., formerly Zeit, is an American cloud platform as a service company.
The company maintains the Next.js web development framework.
OOP
Object-oriented programming (OOP) is a computer programming model that organizes software design around data, or objects, rather than functions and logic. An object can be defined as a data field that has unique attributes and behavior.
Abstraction, encapsulation, inheritance, and polymorphism are four of the main principles of object-oriented programming.
Abstraction lets us selectively focus on the high-level and abstract way the low-level details.
Inheritance is about code reuse, not hierarchies.
Encapsulation keeps state private so that we can better enforce business rules, protect model invariants, and develop a single source of truth for related data and logic.
Polymorphism provides the ability for us to design for dynamic runtime behavior, easy extensibility, and substitutability.