Professional Documents
Culture Documents
JavaScript - All
JavaScript - All
Comments
Numbers
*toFixed(nº d casas decimais)
*toString()
*Assignment
*Comparison
*typeof varWhoseTypeWillBeReturned
Strings
* Escaping char (\)
*length
#None changes the original string, for that, reassign back to it:
*includes(“” [, startPosition]) / startsWith() / endsWith() → check for a substring
*slice(startPosition [, endPosition]) / substring() → extract a substring from it. End position is exclusive.
Estruturas de Controle
*for currentArrayValueVar of array → more for collections like arrays, sets n maps
Arrays
*length
*unshift() / push(item1, item2, …) → add items to its start n end. Returns the new length.
*filter(testFunction) → returns new array with the elements that returned true in test function.
*return →return value when it ends running. Useful in the middle of a result
Object literal
→ to transfer a series of structured, related data items in a request, than individually. Easier than
an array, when you want to identify individual items by name.
*Acces props n meths through dot notation or bracket notation (like associative arrays, accepts not only
literal names but vars too as names)
*this → represents current object, inside it. Useful to manipulate it without mention it literally
*constructor → makes a new object from a function. Initializes, binds this to current object, runs the
fction’s code and returns the new object. Useful if we need many copies of an object, with != values.
Prototype → built-in property of all objects. It has prototype chain. Properties n methods are looked up
in: the object, its prototype then, its prototype’s prototype, etc.
*Object.getPrototypeOf(objNameWhoseProtoWeWant)
Classes
*properties, constructor n methods
*constructor called with the Class’s name → new Class(). Omit constructor in the Class if no need for
initializations.
*inheritance → extends. Initialize the superclass’ constructor first, super(args), then its constructor’s.
*polymorphism
*encapsulation → avoid repeat same code n gives security. #privateVarNameOrMethod (to make it
private).
JSON
*arrays as JSON
*debugger;
Asynchronous JavaScript
→ programming technique, cause potentially long running tasks (HTTP request, camera or microphone
access, file upload, etc.) be non-blocking
*event handler
*callback functions → passed to other functions. Callback hell or the pyramid of doom
*Promise → is the object returned by an asynchronous function. Represents the current state of the
operation.
*promise-based APIS
Fetch API
*responseObj.json() → to get the response data as JSON. It’s also asynchronous. Returns a
promise n the JSON data. Needs then((data)=>).
*promise chaining → useful when the operation needs consecutive asynchronous function calls.
*Promise.all([fetch objects here]) → to handler many fetch objects at once all to be fulfilled. As array of
promises.
*Promise.any() → when you need any one of a set of promises to be fulfilled. It is fulfilled if just
one of the array promises fulfills. If none it is rejected.
*await → used before a call to a function that returns a promise. This makes the code wait at that
point until the promise is settled. Both make async fctions look like sync code.
*your main code and your worker code never get direct access to each other's variables
JavaScript — A high-level scripting language built into browsers that allows you to
implement functionality on web pages/apps. Note that JavaScript is also available in
other programming environments, such as Node.
Browser APIs — constructs built into the browser that sits on top of the JavaScript
language and allows you to implement functionality more easily.
Third-party APIs — constructs built into third-party platforms (e.g. Twitter, Facebook)
that allow you to use some of those platform's functionality in your own web pages (for
example, display your latest Tweets on your web page).
JavaScript libraries — Usually one or more JavaScript files containing custom
functions that you can attach to your web page to speed up or enable writing common
functionality. Examples include jQuery, Mootools and React.
JavaScript frameworks — The next step up from libraries, JavaScript frameworks (e.g.
Angular and Ember) tend to be packages of HTML, CSS, JavaScript, and other
technologies that you install and then use to write an entire web application from
scratch. The key difference between a library and a framework is "Inversion of Control".
When calling a method from a library, the developer is in control. With a framework, the
control is inverted: the framework calls the developer's code.
*Your code interacts with APIs using one or more JavaScript objects (the entry point), which serve
as containers for the data the API uses (contained in object properties), and the functionality the
API makes available (contained in object methods)
*Manipulating documents
*Drawing graphics
*client-side storage
*************************************************************************************
*************************************************************************************
*************************************************************************************
*************************************************************************************
*************************************************************************************
Grammar and types
Basic syntax ( ; to separate commands at the same line. Uses Unicode charset) & comments
(hashbang)
Declarations
Variable scope
Variable hoisting
Data structures and types (7 primitives: null, undefined, BigInt, Symbol. 1 Object)
Literals → values n not variables.
Array literals
Boolean literals
Numeric literals
Object literals
RegExp literals
String literals
Functions
Defining functions
Calling functions (recursive functions those that calls themselves, arguments.callee)
Function scope
Closures (nested functions, where inner function’s resources can’t be used by the outer
function). Can be called like(args1)(args2)
Arguments & parameters (scope chain or name conflict, in name conflict the innermost arg has
precedence). Arguments array-like, very handy when args’re unknown.
*default parameter vs. rest parameter
Arrow functions
*objectName instanceof objectType → returns true or false if the obj’s of that obj type.
Bitwise & logical operators
Conditional (ternary) operator
Date object
set() → set current obj date
get() → get current set date
to() → to return string values from date obj
parse / UTC methods → to parse date string
Seconds / minutes
Hours / Day (of the week)
Date (day number in the month)
Months / Year or FullYear
Text formatting
String literals
String object
Method Description
Return the character or character code at the specified positio
charAt(), charCodeAt(), codePointAt()
string.
Return the position of specified substring in the string or last
indexOf(), lastIndexOf()
position of specified substring, respectively.
Returns whether or not the string starts, ends or contains a
startsWith(), endsWith(), includes()
specified string.
concat() Combines the text of two strings and returns a new string.
Splits a String object into an array of strings by separating the
split()
string into substrings.
slice() Extracts a section of a string and returns a new string.
Return the specified subset of the string, either by specifying
substring(), substr()
start and end indexes or the start index and a length.
match(), matchAll(), replace(), replaceAll(), search(
Work with regular expressions.
)
toLowerCase(), toUpperCase() Return the string in all lowercase or all uppercase, respectively
Returns the Unicode Normalization Form of the calling string
normalize()
value.
Returns a string consisting of the elements of the object repea
repeat()
the given times.
trim() Trims whitespace from the beginning and end of the string.
Template literals
Internationalization
It’s an API for language sensitive string comparison, number formatting, and date
and time formatting. The entry point is in Intl.
Regular Expressions
exec() / test() → RegExp meths
match(), matchAll(), replace(), replaceAll(), search(), and split() → String meths.
*RegExp literal → useful when the pattern’s known n won’t change. Otherwise, use RegExp
constructor
Indexed collections
Arrays
Typed arrays
Keyed collections
Map → a key on a map may only occur once.
Props:
*size → returns its length
Meths:
*clear() → removes everything
*delete(‘keyName’) → removes that key/value pair. Returns true if success,
else false in case that ain’t there.
*get(key) → returns its value, else undefined. Any changes to it will reflect
on the map
*has(key) → returns true if any value related, else false.
*keys() → returns a new iterator with all its keys
*values() → returns a new iterator with all its values
*entries() → returns a new iterator with all its [key, value] pair in each
interation.
*set(key, value) → adds or updates an entry. Returns the map obj, so you
can chain the method call.
*associate metadata
*caching
Meths:
Props:
*size
Meths:
*add(value) → adds the value only if not pre-existing. Returns the set
*clear() / delete(value) / has(value) /
#values() or keys() → returns a new Iterator object with its values.
#entries() → returns a new iterator with all its [value, value] pair in each
interation.
#forEach() → similar to Map’s.
Meths:
*seal(obj) → almost like freeze() but the obj’s still writable since it’s true.
Creating objects
Defining methods
# configurable → true or false. True only if the type of this prop may be changed or if
the prop itself may be deleted.
# enumerable → true or false. True only if the prop shows up in an enumeration of the
obj’s props.
*Data descriptors:
# writable → true or false. True if the value of the current prop is assignable.
*Accessor descriptors:
# get → a fction that serves as the getter of the prop, or undefined if none.
Using classes
Declaring a class
Various class features
*static → indicates its static (prop, meths, etc.)
Why classes?
Promises
Overview: Promises
Guarantees
Chaining
Error propagation
Composition
Timing
● Iterators →object which defines a sequence and potentially a return value upon its termination
*Arrays, Typed arrays, Set n Maps → are all iterables cuz they've the Symbol.iterator in their
_proto_chain
*it[Symbol.iterator] = function* () {
yield 2;
yield 1;
};
Or
const myIterable = {
*[Symbol.iterator]() {
yield 1;
yield 2;
yield 3;
}
}
→ you can call it in a loop or spread operators
*function* gen() {
yield* ['a', 'b', 'c'];
}
gen().next();
// { value: "a", done: false }
● Generators →allow you to define an iterative algorithm by writing a single function whose
execution is not continuous.
*The next() method also accepts a value, which can be used to modify the internal state of the
generator. A value passed to next() will be received by yield. The first value is ignored. Useful to reset
the generator, etc.
Meta programming
The Proxy and Reflect objects allow you to intercept and define custom behavior for
fundamental language operations (e.g. property lookup, assignment, enumeration, function
invocation, etc.). With the help of these two objects you are able to program at the meta level of
JavaScript
● Proxy →The Proxy object enables you to create a proxy for another object, which can intercept
and redefine fundamental operations for that object
*commonly used to log property accesses, validate, format, or sanitize inputs, and so on.
● Reflect →is a built-in object that provides methods for interceptable JavaScript operations. The
methods are the same as those of the proxy handlers.
*Helps with forwarding default operations from the handler to the target
JavaScript modules
Overview: JavaScript modules
*export → placed before any items you want exported out of the module
*export { feat1, feat2, featn}; → used at the file bottom to export features.
● Importing → Once you've exported some features out of your module, you need to import
them into your script to be able to use them.
*Once you've imported the features into your script, you can use them just like they were
defined inside the same file
● Renaming features → .mjs (clarity n development step) for JS module files, instead of .js (build
step).
● Aggregating modules →to import each module's features inside a module object.
*import('./modules/myModule.js')
.then((module) => {
});
In order to maximize the reusability of a module, it is often advised to make the code "isomorphic" —
that is, exhibits the same behavior in every runtime. This is commonly achieved in three ways:
Separate your modules into "core" and "binding". For the "core", focus on pure JavaScript logic like
computing the hash, without any DOM, network, filesystem access, and expose utility functions. For the
"binding" part, you can read from and write to the global context. For example, the "browser binding"
may choose to read the value from an input box, while the "Node binding" may read it from
process.env, but values read from either place will be piped to the same core function and handled in
the same way. The core can be imported in every environment and used in the same way, while only the
binding, which is usually lightweight, needs to be platform-specific.
Detect whether a particular global exists before using it. For example, if you test that typeof window ===
"undefined", you know that you are probably in a Node.js environment, and should not read DOM.
This is preferable if the two branches actually end up with the same behavior ("isomorphic"). If it's
impossible to provide the same functionality, or if doing so involves loading significant amounts of code
while a large part remains unused, better use different "bindings" instead.
Use a polyfill to provide a fallback for missing features. For example, if you want to use the fetch
function, which is only supported in Node.js since v18, you can use a similar API, like the one provided
by node-fetch. You can do so conditionally through dynamic imports:
The globalThis variable is a global object that is available in every environment and is useful if you want
to read or create global variables within modules.