JavaScript Knowledge
Kip Landergren
(Updated: )
Contents#
Overview#
JavaScript is a dynamic, weakly-typed programming language with prototypical inheritance and first class function support. It conforms to the specification document “Standard ECMA-262”, which is written and maintained by Technical Committee 39 (TC39).
ECMAScript standards are referred to either by their “edition” or year, with “ECMAScript 2015” (also known as “ECMAScript 6th Edition” or just “ES6”) being the most recent JavaScript standard to contain major language changes. These changes included modules, classes, promises, and others.
Engines for executing JavaScript include:
- V8, which powers Google Chrome and Node.js
- JavaScriptCore, which powers WebKit, used in Apple’s Safari web browser
- SpiderMonkey, which powers parts of Mozilla Firefox
It is important to note that JavaScript the language is separate from browser APIs (DOM, Canvas, WebRTC, etc).
Core Idea#
Create a scripting language for the web.
Key Concepts#
Prototypical Inheritance#
An object’s [[Prototype]] is a property pointing to the object it inherits from. This forms a chain up to Object whose [[Prototype]] property points to null.
The chain is important for property access: when a property is not found on an object, the next object in the prototype chain is searched, repeating until the property is found or null is reached.
Equality#
Three options:
- === - strict equality
- == - abstract equality
- Object.is - same value equality
The MDN Equality comparisons and sameness article goes over this in depth.
Modules#
Modules are files containing JavaScript code with the constraints:
- use strict; is on by default
- the default scope is local to the module file
- import and export keywords are used to control code access and use
There is no Module keyword.
// ModuleA.js
export const greeting = "hello world";
export default {
foo: "bar",
};
// ModuleB.js
import greeting from "./ModuleA.js"
console.log(greeting);
// ModuleC.js
import { default as lookup } from "./ModuleA.js"
console.log(lookup.foo); // "bar"
// ModuleD.js
import * as ModA from "./ModuleA.js"
console.log(ModA.greeting); // "hello world"
Event Loop#
JavaScript engines are comprised of major components:
- heap, where memory is allocated
- stack, where function calls are added
- queue, where messages are stored
The JavaScript event loop:
- processes functions until the stack is empty
- then processes the next message in the queue
Promises#
A JavaScript Promise represents the execution of a JavaScript function object. This function object, called the Promise’s executor, is invoked with two arguments:
- resolve, a function to be called with a single argument value which will be passed back to the Promise as a resolved value
- reject, a function to be called with a single argument reason which will be passed back to the Promise as a rejected value
The executor’s return value is ignored and the function is expected to work via side effects from resolve and reject alone.
{ const rand = Math.floor(Math.random() * 10); if (rand < 5) { resolve(rand); } else { reject(\<samp>$\{rand} is greater than 4!\</samp>); } return "this return does nothing" });
p0.then((value) => { console.log(\<samp>p0 fulfilled via $\{value}\</samp>); }).catch((error) => { console.log(\<samp>p0 rejected because: $\{error}\</samp>); });`} /> The state of a Promise is determined by the execution of the executor and its respective calls to resolve or reject. It may be one of the following mutually exclusive states:
- “fulfilled”, when a result value is available
- “rejected”, when a result value is not available but a reason (typically an Error) for rejection is available
- “pending”, when not “fulfilled” and not “rejected”
A Promise is considered “settled” when in either state:
- “fulfilled”
- “rejected”
A Promise is “resolved” when:
- it has been “settled”
- its state is “locked in” to match the state of another Promise.
I do not really understand how a Promise can be made to match the state of another Promise. The specification section where this is defined does not elaborate. This StackOverflow answer indicates that matching state occurs when a Promise resolves to (returns?) another Promise, but does not give an example.
Additionally, I find it confusing that the resolve function is so named but the definition of “resolved” includes being in the state “rejected”. This I believe is due to the special case mentioned above of a Promise resolving to another Promise.
A Promise does not imply that the operation will be performed asynchronously. You cannot take a sychronous operation, wrap it in a Promise, and expect it to be executed concurrently. The wrapped operation will be executed synchronously unless and until properly invoked async marked functions containing await are used on asynchronous APIs. At that point execution will be suspended and the event loop is able to process the next task.
Async / Await#
The async keyword is placed in front of function definition to indicate, and ensure, that the function returns a Promise. If the function definition does not return a Promise, async will wrap the result in one.
The await keyword, which can only be used inside async functions, will pause the execution of its successive expression if, at some depth, an asynchronous API like those for IO or timers is called. Execution will resume when the asynchronous API call completes.
await does not imply that execution of the successive expression will be done asynchronously, even if that expression is a Promise.
Understanding Automatic Semi-Colon Insertion#
Use parentheses to control. Example:
function foo(args) {
return
args
}
vs:
function foo(args) {
return (
args
);
}
Terminology#
- binding#(term binding)(term bound)
- 1.
The association of a specific object to
this.Also: bound
- executor#(term executor)
- 1.
The function object wrapped by the
Promise - falsy#(term falsy)
- 1.
The quality of an object that evaluates to
false.Related:
- fulfilled#(term fulfilled)
- 1.
The state of a
Promisewhen a result value is available.Related:
- hoisting#(term hoisting)
- 1.
Term used to provide a conceptual understanding of how variable and function declarations are put into memory during the compile phase; they can be thought of as being “hoisted” to the top of the file.
- key#(term key)
- 1.
An enumerable property of an object.
- own property#(term own property)
- 1.
A property belonging to an object and not a member of its prototype chain.
- peer dependency#(term peer dependency)
- 1.
A dependency that should match the version running on the host (hence “peer”).
Consider this scenario: you are writing a React app foo that has dependencies bar and baz, each of which have dependencies on different versions of
lodash .JavaScript package managers can work around this by installing multiple copies of lodash to satisfy the varying requirements.
Now let’s imagine you want to use qux, a React component library. The only way this library is helpful to you is if it works with your version of React that foo is built with.
If qux declared React as a direct dependency with version constraints that your version of React satisfies: everything would work.
The problem comes when your version of React conflicts with the version constraints: a JavaScript package manager installing a different version of React would not benefit you because you would not be able to use it.
The designation of “peer dependency” allows JavaScript package managers to error out on version conflict rather than trying to satisfy.
- pending#(term pending)
- 1.
The state of a
Promisewhen not “fulfilled” or “rejected”Related:
- rejected#(term rejected)
- 1.
The state of a
Promisewhen a result value is not available but a reason (typically anError) for rejection is available.Related:
- resolved#(term resolved)
- 1.
A
Promisethat is either “settled” or has been “locked in” to match the state of anotherPromise - settled#(term settled)
- 1.
A
Promisethat is either “fulfilled” or “rejected”Related:
- truthy#(term truthy)
- 1.
The quality of an object that evaluates to
true.Related: