Js Engine Flashcards
(142 cards)
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