Javascript

For understanding loops and closures https://stackoverflow.com/questions/16937223/pass-a-parameter-to-filereader-onload-event

Export ….

module.exports = { ….. }

function functionName(argument, callback){
    return asyncPromise.then (response => ….. callback(cbargument)).catch   
}


functionname(argument, () => …)

This is not good! Leads to nested callbacks.

functionName(argument) {
    return asyncPromise.then(response => <do directly what callback would have done>).catch(error => return promise).


}

For (var [key, value] of Object.entries(dictionaryObject)) vs for (var x in/of dictionary object)

JavaScript: Event Loop and stuff

https://stackoverflow.com/questions/21607692/understanding-the-event-loop https://www.youtube.com/watch?time_continue=71&v=8aGhZQkoFbQ What happens when javascript makes an ajax request in a browser? https://blog.bloomca.me/2018/12/22/writing-a-web-server-node.html


On Closures

https://softwareengineering.stackexchange.com/questions/285941/why-would-a-program-use-a-closure https://stackoverflow.com/questions/111102/how-do-javascript-closures-work?rq=1

Closures are a neat way of dealing with the following two realities of JavaScript: a. scope is at the function level, not the block level and, b. much of what you do in practice in JavaScript is asynchronous/event driven. A closure is one way of supporting first-class functions; it is an expression that can reference variables within its scope (when it was first declared), be assigned to a variable, be passed as an argument to a function, or be returned as a function result.

When a function (foo) declares other functions (bar and baz), the family of local variables created in foo is not destroyed when the function exits. The variables merely become invisible to the outside world. Foo can therefore cunningly return the functions bar and baz, and they can continue to read, write and communicate with each other through this closed-off family of variables (“the closure”) that nobody else can meddle with, not even someone who calls foo again in future.

https://medium.com/coderbyte/a-tricky-javascript-interview-question-asked-by-google-and-amazon-48d212890703

Private Variables:

https://lazamar.github.io/closures-private-variables-and-methods-in-javascript/ https://www.joezimjs.com/javascript/javascript-closures-and-the-module-pattern/ https://stackoverflow.com/questions/9772307/declaring-javascript-object-method-in-constructor-function-vs-in-prototype/9772864#9772864 http://www.crockford.com/javascript/private.html https://stackoverflow.com/questions/12180790/defining-methods-via-prototype-vs-using-this-in-the-constructor-really-a-perfo https://stackoverflow.com/questions/310870/use-of-prototype-vs-this-in-javascript

This pattern of public, private, and privileged members is possible because JavaScript has closures. What this means is that an inner function always has access to the vars and parameters of its outer function, even after the outer function has returned. This is an extremely powerful property of the language. There is no book currently available on JavaScript programming that shows how to exploit it. Most don’t even mention it. Private and privileged members can only be made when an object is constructed. Public members can be added at any time.


On Prototypical Inheritance (constructor syntax vs Object Only “Factory function based” syntax) vs Class Based Inheritance (class syntax)

One major drawback to delegation is that it’s not very good for storing state. If you try to store state as objects or arrays, mutating any member of the object or array will mutate the member for every instance that shares the prototype. In order to preserve instance safety, you need to make a copy of the state for each object.


On ‘This’

https://stackoverflow.com/questions/80084/in-javascript-why-is-the-this-operator-inconsistent/80478#80478

On Continuation Passing Style 

https://www.quora.com/What-is-continuation-passing-style-in-functional-programming

On Iterators

https://codeburst.io/a-simple-guide-to-es6-iterators-in-javascript-with-examples-189d052c3d8e


Async Programming

async/await Promise. Promise.reject Promise.resolve Generator Promise.coroutine try catch throw .catch.then Promise.all

Promises and Generators:

Interview question

Interview question: Implement a callback based asynchronous function. The callback handles error cases and correct response cases.

beforeEach(function() {
    sinon.stub(tax, 'calculate', function(subtotal, state, done) {
      setTimeout(function() {
        done({
          amount: 30
        });
      }, 0);
 afterEach(function() {
    tax.calculate.restore();
  });

Generator function with yield keyword is just an iterator, which iterates over the parts of the program. It is used when you have a function which needs to suspend its execution, do some task, then resume execution.

Promise.coroutine(generator function): returns a function. This function, when called, returns a promise to execute the series of taks implicit in generator. This promise is resolved when the done is set true within the generator.

async keyword returns a promise = Promise.couroutine returns a promise. The ‘async’ annotation or Promise.coroutine is syntactic sugar for ‘returns a promise’.

await is nothing but sugar for promise.then syntax. Await doesn’t suspend execution. await or promise.then “unwraps” a promise and either result in the value the promise was resolved with or throws an error if the promise was rejected.

The difference beteen await and x.then() is that you can only use await inside an async function. Right now, top-level await isn’t yet supported, so you might have to make an async IIFE (Immediately Invoked Function Expression) to start an async context.

If a promise resolves normally, then await promise returns the result. But in the case of a rejection, it throws the error, just as if there were a throw statement at that line.

you should not put async callbacks inside of promises. Promisify everything that’s async and then you don’t have these restrictions. TLDR: A function is hard to use when it sometimes returns a promise and sometimes throws an exception. When writing an async function, prefer to signal failure by returning a rejected promise. As a good practice, an asynchronous action should always return a promise. That makes it possible to plan actions after it; even if we don’t plan to extend the chain now, we may need it later.

Promise.reject vs throw() There is no advantage of using one vs the other, but, there is a specific case where throw won’t work. However, those cases can be fixed. Any time you are inside of a promise callback, you can use throw. However, if you’re in any other asynchronous callback, you must use reject. https://stackoverflow.com/questions/33445415/javascript-promises-reject-vs-throw

**Prefer promises to callbacks **

Reference

Prefer using generators with async/await syntax to Promise.coroutine.

Prefer factory functions to constructors/classes.

passing dictionary object instead of parameters allows the function to destructure arguments irrespective of order

Use Object.spread, Object.assign, Object.keys

For loops go through prototype chain as well. might want to check hasOwnProperty

typeof (undefined) && != null

if ()…can return false for 0 or false, not merely undefined or null

28 May 2021