Category Archives: javascript

abstract (typescript)

ref –

  • https://www.tutorialsteacher.com/typescript/abstract-class
  • https://stackoverflow.com/questions/260666/can-an-abstract-class-have-a-constructor?rq=1
  • https://www.typescripttutorial.net/typescript-tutorial/typescript-abstract-classes/
  • https://khalilstemmler.com/blogs/typescript/abstract-class/
  • https://khalilstemmler.com/blogs/typescript/abstract-class/

TypeScript – Abstract Class

Abstraction removes the need to implement all the low-level details upfront; instead, we can focus on the high-level and figure out the specifics later.

Abstract classes are mainly for inheritance where other children classes derive from parent classes.

An abstract class is typically used to:

  • define common behaviors for derived classes to extend
  • cannot be instantiated directly (although regularly parent class can be instantiated)
  • An abstract method does not contain implementation. It only defines the signature of the method without including the method body, which the child class MUST define

We deal primarily with two types of classes in object-oriented programming languages: concretions and abstractions.

Concrete classes are real, and we can construct objects from them to use at runtime using the new keyword. They’re what most of us end up using when we first start learning object-oriented programming.

On the other hand, abstractions are blueprints or contracts that specify the properties and methods that a concretion should have. We can use them to contractualize the valid structure of an object or a class.

another example:

In the previous examples, we used the interface keyword to create abstractions. However, when we speak of abstractions in object-oriented programming, we’re generally referring to one of two tools:

  • interfaces (i.e.: the interface keyword) or
  • abstract classes (i.e.: the abstract keyword in front of a class)

We want to focus on defining a contract containing all the necessary things that a subtype needs to provide if they want it to work with the base type — and leave it to developers to implement them?

This satisifes:

Liskov Substitution Principle — since we define valid subtypes, each implementation should work and be interchangeable as long as it implements the contract.

Dependency Inversion — we do not directly depend on the concretions; instead, we rely on the abstraction that the concretions depend on; this keeps our core code unit testable.

Defining common properties

Within this Book abstraction, we can then decide on the contract for a Book. Let us say that all Book subclasses must have author and title properties. We can define them as instance variables and accept them as input using the abstract class constructor.

Defining common logic

We can then can place some of the common logic within the Book abstract class using regular methods.

Remember that an abstract class is an abstraction comparable to an interface. We can’t instantiate it directly. Trying anyway for demonstration purposes, we’ll notice that we get an error that looks like this:

We’ll introduce one of our specific types of Book concretions — the PDF class. We extend/inherit the abstract Book class as a new subclass to hook it up.

Since PDF is a concrete class, we can instantiate it. The PDF object has all of the properties and methods of the Book abstraction, so we can call getBookTitle and getBookAuthor as if it were originally declared on the PDF class.

Defining mandatory methods

Abstract classes have one last important feature: the notion of the abstract method. Abstract methods are methods that we must define on any implementing subclass.

In the abstract class, we define them like so:

Notice that there is no implementation for the abstract method? That’s because we implement it on the subclass.

Demonstrating with the PDF and an additional EPUB subclass, we add the required abstract method to both of them.

Failing to implement the required abstract methods will fail to make the class complete and concrete — this means we’ll run into errors when trying to compile our code or create instances.

Use cases (when to use abstract classes)

Now that we know the mechanics behind how abstract classes work, let’s talk about real-life use cases for it — scenarios you are likely to encounter.

There are two primary use cases for needing to use abstract classes:

  • Sharing common behavior
  • Template method pattern (framework hook methods)

Sharing Common Behavior

Let’s say that we definitely need to fetch data from:

a Users API located at example.com/users
a Reviews API located at example.com/reviews

What’s the common logic?

Setting up an HTTP library (like Axios)
Setting up interceptors to set up common refetching logic (say, like when an access token expires)
Performing HTTP methods

Here, we’ve placed the low-level behavior within a BaseAPI abstraction. Now we can define the high-level behavior — the rich stuff — in the subclasses.

So now we can get all sort of data whether it us Users, Reviewers…etc.

Template Method Pattern ( framework hooking )

So then, a simplistic version of the abstract class for a component could look like the following:

And then to use it, we’d need to extend the Component abstraction and implement the render method.

We need to implement the render method because it is a critical part of the work involved with deciding what gets created on screen.

An abstract class is a suitable tool for this problem is because there is an algorithm running behind the scenes — an algorithm in which the render step is but a single step amongst many.

We can see that there are three distinct phases to React: mounting, updating, and unmounting. React’s abstract class further gives us (the client developer) the ability to customize our components by connecting the ability to hook into various lifecycle events. For example, you can perform some behavior as soon as your component mounts (componentDidMount), when it updates (componentDidUpdate), and when it’s about to unmount (componentWillUnmount).

so the algorithm may look like this:

And now, a customized component subclass can plug in behavior within those key lifecycle hook methods. This is the concept of Inversion of Control.

So as a framework designer, the Template Method design pattern is attractive when:

  • You need the client to implement a step of the algorithm → so you make that step an abstract method
    You want to provide the ability for clients to customize behavior at various steps of the algorithm → so you expose optional lifecycle methods to the client

Supplementals

The following abstract class declares one abstract method find and also includes a normal method display.

In the above example, Person is an abstract class which includes one property and two methods, one of which is declared as abstract.

The find() method is an abstract method and so must be defined in the derived class. In other words, the Employee class derives from the Person class and so it must define the find() method as abstract.

The Employee class must implement all the abstract methods of the Person class, otherwise the compiler will show an error.

Note:
The class which implements an abstract class must call super() in the constructor.

GET POST using fetch from client to web api

Using fetch, we get a GET request on a web API using Azure authentication and passport

node server

client

Using fetch, we get a POST request on a web API using Azure authentication and passport

node server

client

Passing a form data to the Web API with no authentication

client

Differences between es6 arrow functions and es5 functions

ref – https://blog.logrocket.com/anomalies-in-javascript-arrow-functions

Named function parameters

Initially, we have an issue where if we create a function with duplicate parameter name, JS will use the latest name as the parameter.

As we can see, the first parameter is a duplicate; thus, it is mapped to the value of the third argument passed to the function call, completely overriding the first argument passed. This is not a desirable behavior.

The good news is that this behavior is not allowed in strict mode. Defining a function with duplicate parameters in strict mode will throw a Syntax Error indicating that duplicate parameters are not allowed. At compile time, it will throw an error:

Unlike regular functions, arrow functions do not allow duplicate parameters, whether in strict or non-strict mode. Duplicate parameters will cause a Syntax Error to be thrown during compile time.

Function Overload

Function overloading is the ability to define a function such that it can be invoked with different call signatures (shapes or number of arguments). Arguments binding for JavaScript functions makes this possible.

However, for arrow function, arguments is not defined.

Unlike regular functions, the arguments binding does not exist for arrow functions. However, they have access to the arguments object of a non-arrow parent function.

For arrow functions, we have ES6 parameters.

– A rest parameter is not the same as the internal arguments object inside the function. The rest parameter is an actual function parameter, while the arguments object is an internal object bound to the scope of the function.

– A function can only have one rest parameter, and it must always be the last parameter. This means a function can have a combination of named parameters and a rest parameter. In other words, if you declared other parameters, obviously, the rest parameter will not capture all the function’s arguments. The individually declared parameters will be bound to their respective param names. Thus, from a rest parameter sense, it will NOT be able to reach them.

– By definition, when it is the only function parameter, it captures all function arguments. On the other hand, the arguments object of the function always captures all the function’s arguments.

– The rest parameter points to an array object containing all the captured function arguments, whereas the arguments object points to an array-like object containing all the function’s arguments.

Constructor functions

When a regular JavaScript function is invoked with the new keyword, the function’s internal [[Construct]] method is called to create a new instance object and allocate memory. After that, the function body is executed normally, mapping this to the newly created instance object. Finally, the function implicitly returns this (the newly created instance object), except a different return value has been specified in the function definition.

Also, all regular JavaScript functions have a prototype property. The prototype property of a function is an object that contains properties and methods that are shared among all instance objects created by the function when used as a constructor.

Unlike regular functions, arrow functions can never be called with the new keyword because they do not have the [[Construct]] method. As such, the prototype property also does not exist for arrow functions.

Arrow functions cannot be used as constructors. They cannot be called with the new keyword. Doing that throws an error indicating that the function is not a constructor.

Also, because arrow functions cannot be called with the new keyword, there is really no need for them to have a prototype. Hence, the prototype property does not exist for arrow functions.

This

arrow functions manipulate ‘this’ to reference its parent context, to whatever its nearest non-arrow function’s this context.
es5 functions’s this references the calling object.

If you run this code, you will see that the countdown timer seems to be broken. It keeps logging NaN on the console infinitely.

The problem here is that inside the callback function passed to setInterval(), this points to the global window object instead of the newly created instance object within the scope of the Timer() function. Hence, both this.seconds and this.interval are undefined.

to fix, use .bind function:

or arrow function:

Error Boundary in React

ErrorBoundary.js

Error boundaries are components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed.

App.js

Pure components in React

ref – https://medium.com/technofunnel/working-with-react-pure-components-166ded26ae48
https://en.wikipedia.org/wiki/Pure_function
https://stackoverflow.com/questions/52680508/can-pure-functions-be-asynchronous
demo

Pure Functions

First, let’s talk about pure functions.

The definition of Pure Function says that for specific input parameters, we always have a specific output. The output is solely dependent on Input parameters and no other external variable.

Wikipedia defines it as:

  • Its return value is the same for the same arguments. 1 to 1. For a particular input, you won’t get different outputs. No mutation of local static variables, non-local variables, mutable reference arguments or I/O streams
  • Its evaluation has no side effects (no mutation of local static variables, non-local variables, mutable reference arguments or I/O streams).

example:

It uses non-local variable initialValue. So it is impure.

The code specified above is another example of the impure function, where the function is modifying the global variable getInitialValue, which does not lie under the scope of this function. Modifying this variable results in the introduction of Impurity to the function, making it Impure.

The function given above defines the output on the basis of the input parameter only.
No outer variables is adding its impact to the output.
Also, we can see that the function does not modify any other variable that does not belong to this function. Hence it adheres to the concept of Pure Functions.

Browser optimizations via Pure Functions

Pure Functions have a huge performance benefit during execution on the Browser.

Picture a scenario where a specific Pure Function is getting called multiple times.
The Application calls for the same function multiple times with the same parameters — assume “add(10, 20)”.
After executing it multiple times, the Chrome V8 Engine tries to optimize the code further by storing the execution result of the following function call. On the next call to the same function, with the same parameter, instead of executing the function again, the cached result is returned. Hence enhancing the Application Performance.

Functions should not introduce side effects

If the application updates certain data that is observable outside the called function, it can be considered a side effect introduced by the function.

Here are a few scenarios:

  • Modifying any external variable or object property (DOM)
  • – self explanatory. You use or modify outside global variables such as the document object.

  • Logging data to the console
  • – Similar to DOM, it is using outside object (console). Also, it prints something onto the screen.

  • Writing Data to a file
  • – It changes data to a file, which is global.

  • Writing data to the network
  • – Modifies network resources, which is global.

  • Triggering any external process
  • Calling any other (impure) functions with side-effects
  • Making Asynchronous Data Calls
  • – asynchronous actions usually is impure.

    Most things that we use asynchronous functions for are inherently side-effect(ful): I/O, network stuff, timers. But even if we ignore those, promises alone rely on some kind of global state for their asynchrony: the event loop. This violates purity.

    Pure Components

    Pure Components in React are components which do not re-renders when the value of state and props has been updated with the same values.
    If the value of the previous state or props and the new state or props is the same, the component is not re-rendered. Pure Components restricts the re-rendering ensuring the higher performance of the Component.

    Features of React Pure Components

    • Prevents re-rendering of Component if props and state is the same
    • Takes care of “shouldComponentUpdate” implicitly
    • – It is the same as Component except that Pure Components take care of shouldComponentUpdate by itself, it does the shallow comparison on the state and props data. If the previous state and props data is the same as the next props or state, the component is not Re-rendered.

    • State and Props are Shallow Compared – standard arrays won’t work anymore as pushing a value results in the same array. What we need to do is use dot notation to create another array, then push the value
    • Pure Components are more performant in certain cases

    Similar to Pure Functions in JavaScript, a React component is considered a Pure Component if it renders the same output for the same state and props value. React provides the PureComponent base class for these class components. Class components that extend the React.PureComponent class are treated as pure components.

    Pure Components Restricts Re-rendering

    Let’s look at this Component where we extend from standard Component. It is a impure component because we did not extend from PureComponent.
    What makes it Impure?

    Notice we do setInterval where we do a setState every 1 second.

    When the state gets set, it changes, so our virtual DOM gets diff-ed. Once it diffs, it writes the changes to the real DOM. We do this every second. However, the UI never changes because nothing changes. We’re drawing the same thing over and over again. There is effectively no difference in the UI — the new values are unchanged. Re-rendering, in this case, is an overhead.

    In order to solve this problem, we introduce…

    Pure Components

    They compare the initial and final values for the state and props variables. If there is no difference between the two, they won’t trigger the re-rendering logic for the component.

    Each time the state or props are updated it compares the previous and next value — if the values are the same the Render function is not triggered. Performance is then improved by not calling “render” repeatedly.

    Props and State Changes are Shallow Compared

    In Pure Component, the changes in react “props” and “state” is Shallow Compared to know whether they have changed. If they have changed, it renders. If it doesn’t, it does not render.

    Before we proceed further, we need to understand the concept of Shallow Comparison in JavaScript. The values saved in the variable can be either a primitive or reference type.

    Example “var a = 10”, the value saved in the variable “a” is of primitive type.

    The data stored in Objects and Array can be referred to as Reference type data. Comparing Primitive Values is not a concern.

    Problems arise when we have reference values during the comparison.

    Because the comparison used is shallow (only compare values), then the == will return true. However, these are actually two different objects. So even though their value may the same, their address reference is different. They are two different objects.

    In this example, we’re only dealing with one object. We have two references pointing to it. Thus, value comparison between the two references will be the same.

    We can also use spread operator to create a new object, and then copy the values over.

    IN this example, we create a whole new object with reference cloneData pointing to it. We then copy all properties/values from userInfo into it.
    Thus in the end, we have two objects, with same properties and values. One has reference userInfo pointing to it. The other has reference cloneData pointing to it. cloneData == userInfo will return false because the references are pointing to different memory locations.

    This issue with Shallow Comparison

    Say we have a reference pointing to an object with an array.
    We then push 6 onto it. When the PureComponent does a comparison, it will see that the before state’s userArray (and after state’s userArray) are ‘==’ (value equal) because they are pointing to the same object.

    But its clear that they are not the same. Before state’s userArray is 1,2,3,4,5. After state’s userArray is 1,2,3,4,5,6.

    In the case when the props and state changes are made to primitive type variable,
    state and props changes to reference variable may lead to incorrect results and inconsistent rendering.

    The simple answer to resolving the shallow issue is to work with immutable data using dot operator

    In the example above, we can see that comparing reference variables can lead to a problem — only the address of the object are compared before and after the update. Since we’re comparing references, the address still remains the same and the Pure Component does not detect any changes and does not re-render. We can resolve this by creating a new instance of the state variable if it represents the reference type.

    we’re creating a new reference array using the spread operator. When the setState is called, the component looks for the reference of a previous array object and a new array object is created. The reference is different since this is a new instance of the array, so the object has a new address. Now the pure component will get to know that the data has been updated, the “render” life cycle will be invoked and the component will be re-rendered with correct values.

    Example

    React.memo() does the same as PureComponent but it does not check for changes in state, only in props. Hence, I will use React.memo in functional component here as an example.

    npx create-react-app my-app
    cd my-app
    npm start

    Then in /src, create MyPureComponent.js:

    Basically, we initialize an array with a, b, c. Every time we click, we add the next few letters d, e, f, g….etc. We do this by using number 100, incrementing it, and getting the ascii code for it. Then we append that letter onto the array.

    In index.js, we use our component.

    Run the app and start clicking the button.

    As you can see, after doing shallow comparison of the previous prop to current prop, it gets the same reference value of the object. Thus, it never renders.

    The fix here is to re-create the array and then do the push. That way, whenever you manipulate the array, you put the results onto a new array. Thus when the objects are compared, they are not the same, and thus triggers the render.

    The other thing you can do is to use React.memo’s second parameter with a areEqual function

    Let’s look at another example where we start off with NOT using a comparator. We are erroneously using two references to point to an array object. When we update this array, our sub component does not update because it does a shallow compare on the same array object.

    When we run it, we see that in the subcomponent, nothing gets re-render because its shallow comparison of prevProp and nextProp comes out to be true.

    We fix it by using […arr] so that it creates a whole new objectArray, then copying all the values over. Memo will shallowly compare against two different objects, which then will actually correctly re-render because it will return false due to the two array objects being different.

    Now as you add in additional letters, you’ll see that the sub component re-renders.

    Using Comparator Func

    The code stays the same. All we need to do is to make sure we stick a comparator function in our memo’s 2nd parameter.

    The handling of adding a letter stays the same.

    then create an areEqual comparator:

    We default it to return true because we don’t want it to re-render for now. We want to see the previous prop and next prop.

    Great. We see that there is a difference. This is because the previous array is [‘a’, ‘b’, ‘c’]. We setArr to a new Arr that is a totally different array object by using […arr].
    That way, we can see that both props are different.

    Now let’s implement areEqual. Because our previous and next array data are different, we can actually make some decisions. If they are of different length, we re-render. If they are of different characters, we re-render. Otherwise, we don’t render.

    Full Code

    Copy and paste into App.js

Store it into React state or Redux state?

ref – https://spin.atomicobject.com/2017/06/07/react-state-vs-redux-state/
https://stackoverflow.com/questions/39977540/can-redux-be-seen-as-a-pub-sub-or-observer-pattern

React state

React state is stored locally within a component. When it needs to be shared with other components, it is passed down through props.

In practice, this means that the top-most component in your app needing access to a mutable value will hold that value in its state.

If your top most component needs access to a value that is changeable, you need to hope it in React state. If this state is shared with other components, it needs to be passed through props.

If it can be mutated by subcomponents, you must pass a callback (into the subcomponent) to handle the update in the top-most component.

If your children components need to change this value, your parent component should pass a callback into your child component. That way when the child component changes the value, it can pass it back up to the parent component so it can update it. That way, the parent component is not holding the old value, while the child component has the newest updated value.

Redux state

The need of something like Redux when you have a more complicated application, with top-level components that need to talk to each other (actions) and somehow share some state.

Any component that needs access to a value may subscribe to the store and gain access to that value. Typically, this is done using container components. This centralizes all data but makes it very easy for a component to get the state it needs, without surrounding components knowing of its needs.

Redux is a library to manage shared state between components and to coordinate state mutations. Redux uses a pub/sub pattern.

It has a subscribe method that is used by components to subscribe to changes in the state tree. Normally you don’t use store.subscribe directly, as the Redux-React bindings (Redux’s connect basically) do that for you. The store then emits the changes.

Consider also that it’s perfectly fine to keep using the components internal state together with Redux. You can use the internal state to store state you don’t need/want to share with other components.

Some Guidelines on where to store state

Duration

Different pieces of state are persisted for different amounts of time. I loosely categorize time into these groups:

Short term: data that will change rapidly in your app

Short term data will likely change rapidly. At the simplest level, this includes the characters present in a text field as the user types. I would also extend this to include data in an entire form; this data can be considered a work in progress until the form is submitted. This type of data can be stored in local React state. I would even include things like how to filter a list of items, and whether or not to show or hide completed items in a to-do app (assuming it is not tied to user preferences).

Medium term: data that will likely persist for a while in your app

By medium-term state, I mean state that will stick around while the user navigates your app. This could be data loaded from an API, or any changes that you want to be persisted up until a page refresh.

However, after submitting a form, I would store the state in the Redux store. As an example, if a user submits a form updating their profile information, it would make sense to store this in Redux.

Long term: data that should last between multiple visits to your site

This is state that should be persisted between refreshes of the page or between separate visits to the page. Since the Redux store will be created anew when refreshing, this type of data should be stored somewhere else (likely to a database on a server or into local storage in the browser).

Breadth of Use

Another consideration is how many components in your React app need to access the state. The more state needs to be shared between different components in your app, the more benefit there is to using the Redux store. If the state feels isolated to a specific component or a small part of your app, React state may be a better option.

Depth of passing down props

React state should be stored in the most top-level component for which a subset of its subcomponents will need access to the state. Sometimes, this can mean many layers between the component storing the state and the subcomponents that render the data, and each layer means another prop must be propagated down the virtual DOM.

Parent-to-Child prop passing and callback propagating works great if you only need to pass the state down one or two levels into the subcomponents. But beyond that, it can feel tedious and require edits to many components every time you find a subcomponent needs access to new state. In cases like this, I find it much easier to store the state in Redux and use a container component to pluck the desired data from the store.

Unrelated components needing the same state

It could also be that multiple, relatively unrelated components need access to the same state. Take the above example of a form to update a user’s profile. The component here should receive the initial user profile in its props. You might also have a header component with a subcomponent that displays the user’s username or related data.

You could, of course, take passing down props to the extreme, in which your top-level component knows about the user’s profile and passes it to the header, which passes it to a subcomponent (and maybe further), and also passes it down to the profile-editing component. However, this requires a lot of management between the whole virtual DOM.

This type of solution is solved much more cleanly by storing the profile in the Redux store, and allowing container components around the header and profile-editing component to grab data from Redux’s store.

Ability to Track Changes to the State

Another time to choose Redux is when you need to track changes to state:

  • Maybe you want to replay events.
  • Maybe you want to implement undo/redo in your app.
  • Maybe you just want to log how state is changing.

In cases like these, Redux is a great solution; each action that is created is an artifact of how the state changes. Redux makes all these tasks simpler by centralizing them in a single store.

Event Loop (JS)

ref – https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop

So the runtime in our web browser works like so.

– We have a call stack that contains the execution contexts.
– We have a callback queue sitting and waiting.
– We also have a Web API section

  • Objects created in memory are stored in the heap.
  • Execution context happens on the callback.
  • We have a Web API that runs code used by the browser. It executes events and will place code in either the callback queue or other data structures.
  • We also have a callback queue that receives callback functions whenever an an event in the Web API is done or executed.

Say we start off with code like so

Thus, when we start the program, we start with an execution context for global scope.

It executes the first line of code, which is sync.
We then move on to the next line of code.

This will load up an image asynchronously. Thus, the loading of the image happens in the Web API and we let the async tasks run.

We move on to the next line of code:

So now, in the Web API, we have this callback function added. Our Web API keeps track of all these callbacks.

So here as you can see, Web API has the current async operation going…and maintains a callback. This is so that when the async operation of loading up the image is done, it has a valid callback to execute. The callback will stay there until load event is emitted. This is why we want to add the event listener for when the image finishes loading.

Having telling the Web API to load an image, and declaring a callback for when load is done, we now move forward to the fetch operation:

As always, the async fetch operation will happen in the Web API’s environment. Otherwise, we’d be blocking the call stack if we were to execute it using the execution context.

The Web API appends it to its running async operations and now have two async operations going:

Finally we use the then method returned by the fetch function. And this will also register a callback in the Web API’s environment. So we can react to the future resolved value of the promise.

In other words, we place the callback from then then in our Web API. This is so that when fetch operation is completed, it will know to execute the callback provided to then.

Now our Web API environment has two async operation working, and two callback to execute when they are done.

The execution goes forward and processes other code…

Now, comes the good part. Our loading of the image async operation is done! It signals with the load event. Load event has emitted. The callback for this event is then put into the callback queue.

Now, we DO NOT execute this callback right away. Instead, we now put this callback in the callback queue.

Callback queue is like a todo list. Whereas the event loop is an executor.

There could be other callbacks. Then our new callback would be queued and wait until the others are done. This callback will execute when the event loop has finished the other callbacks in the queue. It decides when each callback is worked upon.

This has implications.

Hence, keep in mind that if you decide to use setTimer and wait 5 seconds before putting a callback inside the callback queue, it doesn’t mean your callback will be executed at exactly 5 seconds later. It may be that the callback queue is still processing other queues in front. This will take whatever time those operations specify to be. And then, then they are done, the event loop will come to your callback and execute it.

Hence, when working with timers, just remember that the time you specify in milliseconds is the fastest time that your callback will execute.

Keep in mind that the callback queue also keeps callbacks from DOM events like clicks, or key presses.

DOM events are not async, but they still callback queue to run their attached callbacks. So if a click callback executes on a button with an event listener, it works in the same way that it stays in the event queue until others are finished. So if you somehow have a callback that takes some seconds IN FRONT of a button callback, then your button presses will not work. It will need for the hanging callback in the queue to finish, the event loop processes the button callback, which will then make your button presses work.

The event loop looks into the call stack. Aside from the global context, is it empty?

The Event Loop Tick

If the stack is empty, this means no code is being executed. It takes first callback from callback queue and put it onto the call stack to be executed. This is called the Event Loop Tick

It orchestrates javascript runtime.
Javascript language itself has no sense of time.
Everything that is async, does not happen in the engine.
Its the runtime that manages the async behavior, and it is the event loop that decides which code gets executed next.

The event loop got its name because of how it’s usually implemented, which usually resembles:

The Web API environment, the callback queue, and event loop all make it possible that async operations are executed in a non-blocking way, while using only 1 thread of execution in the engine.

The MicroTask Queue

Callbacks of Promises have priority over other callbacks by using the Microtask queue

So now say the data arrives, and fetch is done. Callback related to promises, actually DO NOT go into the callback queue. Instead, callbacks of promises go to a special queue for microtasks queue.

It is special because it has priority over callback queue. It will run ALL of the microtasks until it is empty. Only then will it process the callback queue again.

The way that it runs microtasks is the same as it would for callback queue. It puts the tasks onto the execution context to be executed. Note that if any microtasks add another microtask, then naturally the new microtask(s) will be processed until the microtask queue is empty. Only then will the callback queue continue to be processed.

Therefore, note that microtasks can starve a callback queue.

A Quick Example


output:

Test start
test end
Resolved Promise 1
0 sec timer!

If microtask takes long time to run, then our timer tasks on the callback queue will be blocked for that amount of time.

So as you can see there will be few seconds when Promise #2’s callback is executing on the microtask queue because the loop from our callback in Promise #2 is running. Once its done, it will log its text, and then finally, the timer’s callback will run on the callback queue.

output:

Test start
test end
Resolved Promise 1

…then a few seconds here because the loop from our callback in Promise #2 is running.

Resolved Promise 2
0 sec timer!

Additional Information

A JavaScript runtime uses a message queue

It is a queue that contains type Message.

Each message object in the queue has a reference to an associated function.
The Event Loop decides when to call the referenced functions.

queue.waitForMessage() waits synchronously for a message to arrive. Because Javascript is single-threaded, it can only do one thing at at a time. It can only processNextMessage if it has nothing to do (waiting).

But if a new message comes into the queue, it will be busy adding it to the queue. Thus in that situation, it cannot processNextMessage. It must first finish adding to the Queue. Then when no more Messages comes in, it will go into waitForMessage status, and thus be able to ProcessNextMessage

Processing Message

Each message is processed completely before any other message is processed.

Pro
This offers some nice properties when reasoning about your program, including the fact that whenever a function runs, it cannot be pre-empted and will run entirely before any other code runs (and can modify data the function manipulates).

This differs from C, for instance, where if a function runs in a thread, it may be stopped at any point by the runtime system to run some other code in another thread.

Con
A downside of this model is that if a message takes too long to complete, the web application is unable to process user interactions like click or scroll. The browser mitigates this with the “a script is taking too long to run” dialog. A good practice to follow is to make message processing short and if possible cut down one message into several messages.

How Message are Added

In web browsers, messages are added anytime an event occurs. An event occurs whenever we attach an event listener to the element like so:

We have an element with the id News. We put a click handler on that element. Now, whenever the user clicks on that element, we can process it the way we like.

When the click happens, an event occurs, and the callback function in the example gets added to the queue as a Message. Similarly, any other event will be added as well. If there is no listener, the event is lost.

Example

The function setTimeout is called with 2 arguments: a message to add to the queue, and a time value (default is 0).

The time value represents a delay in milliseconds. After the delay, the message (anon function provided) will then be pushed into the queue. In other words, when setTimeOut executes, the delay happens instantaneously. After two seconds, our anon function that logs hello will be pushed onto the queue.

If there is no other message in the queue, and the stack is empty, the message is processed right after the delay. However, if there are messages, setTimeout’s anon function will have to wait for the other messages in the queue to be processed. For this reason, the second argument indicates a minimum time — not a guaranteed time.

Basic setTimeout Example

The code gets executed synchronously. However, all async operations such as our setTimeout be placed into our queue. The thing is, Synchronously, our code gets pushed onto the queue first. Even though the setTimeout is wedged in between, the dely starts to run after our code is placed into the queue.

So the code gets pushed onto the queue. Async operations will obviously not run because it has to do the delay first. Thus, as the sync code is being run (our while loop), the 500 ms delay is happening. Then when the 500 ms is up, it then places the async operation (our anon function that logs) onto the queue. Let’s look at some drawings to depict this situation:

But since our while loop is still running, we can’t process the async function yet. We need for the while loop to finish running.

– First, we get a starting timestamp in seconds. Then use while loop to continuously get another timestamp in seconds.
– We subtract the second timestamp from the initial timestamp to get the difference.
– Because the difference is less than two, we repeat the loop. As time moves forward, this difference gets bigger.
– We keep doing this until the difference is two seconds.
– When this happens, we break out of the loop. This finishes our task in the queue.

The queue then remove our while loop, and then moves on to the next task, which is our console log.

Therefore, if there are messages, the setTimeout message will have to wait for other messages to be processed. For this reason, the second argument (delay) indicates a minimum time — not a guaranteed time.

From this example, you’ll be tempted to ask…if we change the dealay from 500 ms to 0ms, wouldn’t the function in setTimeout run exactly AFTER the first line of code?

OUTPUT:
Good, looped for 2 seconds
Ran after after 2 seconds

Thus, as the output shows, the answer is no.

Here’s why.

Zero Delay

Zero delay doesn’t actually mean the call back will fire-off after zero milliseconds. Calling setTimeout with a delay of 0 (zero) milliseconds doesn’t execute the callback function after the given interval.

The execution depends on the number of waiting tasks in the queue. In the example below, the message this is just a message will be written to the console before the messages in the callback gets processed, because the delay is the minimum time required for the runtime to process the request (not a guaranteed time).

We enter all the synchronous code into the queue first. Then we place the setTimeout async functions in according to delay.

In our case, our 3 sync code lines starts executing. As its running, our delay of 0 starts for the setTimeout async operations. We immediately place cb1 function into queue.

Then the thread continues to process the sync code for a step. Then it comes back to our async operations and places cb1 anon function into the queue.

1) Puts the sync code (all 3 logs) into the queue
2) starts processing the sync code
3) delay of 0 is executed
4) logs ‘this is the start’
5) queue cb into the queue
6) logs ‘this is a message’
7) queue cb1 into the queue
8) logs ‘this is the end’
9) pops sync code
10) executes cb and logs ‘Callback1…’
11) dequeue cb
12) execute cb1 and logs ‘Callback2…’
13) dequeue cb1

Never Blocks

A very interesting property of the event loop model is that JavaScript, unlike a lot of other languages, never blocks. Handling I/O is typically performed via events and callbacks, so when the application is waiting for an IndexedDB query to return or an XHR request to return, it can still process other things like user input. This is parallel programming. The single thread work between multiple tasks at the same time.

Legacy exceptions exist like alert or synchronous XHR, but it is considered a good practice to avoid them. Beware: exceptions to the exception do exist (but are usually implementation bugs, rather than anything else).

Mixins in JS

ref – https://blog.bitsrc.io/understanding-mixins-in-javascript-de5d3e02b466

Mixin is a way properties are added to objects without using inheritance — Darren Jones
Mixins are a form of object composition, where component features get mixed into a composite object so that properties of each mixin become properties of the composite object. — Eric Elliot

Let’s create a destination object to contain all the data.

Then we create a whole bunch of other objects with properties.

Finally, we’ll write our custom assign to “mixin” these objects with properties into our destination object like so:

The result of mydetails would be:


{surname: “qi ji”, firstname: “ricky”, occupation: “Software Developer”}
surname: “qi ji”
firstname: “ricky”
occupation: “Software Developer”
__proto__: Object

It mixed in all the properties of the other objects.

Object as hash, and looping through its keys and values (JS)

Scope vs Context in Javascript

ref –

  • https://medium.com/better-programming/scope-vs-context-in-javascript-b31818f58558#28ec
  • https://stackoverflow.com/questions/14328519/different-in-scope-and-context-in-this-javascript-code

scope has two levels: global scope and local scope.

Global scope refers to variables that are accessible anywhere because they are declared outside of any individual functions or methods — usually at the top of the file. They exist in the global space, ready to be called upon at any time.

Local scope refers to variables that are accessible within the boundaries of their function. In this example, we have our initial declaration of the variable dog at the top of our file, which is assigned to the string of “goodBoy.” Immediately below, we console.log the dog variable.

As expected, this first console.log prints ‘good boy,’. Then, we have a function of showScopeExample(), which reassigns our dog variable to the string of “bad boy”.

Our re-declaration of dog inside of showScopeExample() is locally scoped. The easiest way to know this is to look at its location. The re-declaration lies in between opening and closing curly brackets, which act as barriers to the relevancy of these variables.

Limiting the accessibility of the variables declared inside of functions allows us to reuse variable names that may apply to separate parts of our code. Locally scoped variables also prevent our code from having tens or hundreds of global variables floating around the global space unnecessarily. It’s also good practice to exercise proper abstraction in our JavaScript by limiting access to variables to areas where they are needed.

In other words, Scope defines the way JavaScript resolves a variable at run time. There is only two scopes in JavaScript — global and function scope. Moreover, it also deals with something called “scope chain” that makes closures possible.

Context

Context refers primarily to the use of the keyword ‘this’. The value of ‘this‘ depends on where it is being invoked.

First Rule – Invoking this in the global space will return the entire window object. This is because the window object is the starting point of all the code we write.

But what happens if we invoke this somewhere other than the global context?

Second Rule – If we invoke this in the context of a new object, it will return that object, just as it returned the entire window object.

newContextObject.invokeThisInNewContext();

It returns the entire newContextObj. When it is invoked in the context of an object, ‘this‘ will refer to that object.

Third Rule – In JavaScript, we use classes (or function constructors) to create multiple instances of objects that share properties, even though those properties may differ in value.
By using new, it will return us an instance, where the ‘this’ is pointing to the instance itself. The ‘this’ is can be referenced within the the class/function constructors and its methods.

Furthermore, a context of a function is the value of this for that function — i.e. the object the function is called as a method of.

You can invoke this function in different contexts like this: