All posts by admin

classes (js)

  • https://reinteractive.com/posts/235-es6-classes-and-javascript-prototypes
  • https://levelup.gitconnected.com/using-classes-in-javascript-e677d248bb6e?gi=5ba413dea026

Why do we need classes?

Classes are simply templates used to create new objects. The most important thing to remember: Classes are just normal JavaScript functions and could be completely replicated without using the class syntax. It is special syntactic sugar added in ES6 to make it easier to declare and inherit complex objects.

We create a class like so:

We declare scoped variable in constructor for privacy.

So, a class like this:

translates to this:

Constructor

There can be only one special method with the name “constructor” in a class. Having more than one occurrence of a constructor method in a class will throw a SyntaxError error.

A constructor can use the super keyword to call the constructor of a parent class.

If you do not specify a constructor method, a default constructor is used.

Then we implement getter/setter functions for it and attach them to the this object.
Whenever we attach functionality and property to this, its public.

We can then declare other functions that use private properties such as _name.

For example, if we want to implement private removeLastNode that accesses these private properties/functions, we do so in the constructor because removeLastNode can access _name, _head, _tail by scope. removeLastNode is not visible to the outside.

public functions that uses private properties/functionalities

Now, say we want to implement remove function that wants to access our private function and private properties, we simply implement the public function inside of the constructor, and access those private functionality and properties via scoping.

Notice our remove function is public because it is attached to this.
It accesses private properties such as _head due to scoping.
It accesses private functions such as removeNodeAtHead(…) due to scoping.

functions

functions are attached to the this object, and are public.
If the functions want to use use private properties, they must be in the same scope as the private properties/functionalities, which are in the constructor as shown previously.

In this case, if the functions are outside of the constructor, they use private variables through get/set functions that are exposed on the this object.

functions attached to this are added to the prototype

Take this example, class Test.

Any functions/properties added to Test.prototype is shared among all instances.
Any functions/properties added outside of the constructor function is added to Test.prototype and is hared among all instances.
Any functions/properties added inside of the constructor belongs to the instance itself.

you can check like so:

you can also simply input the code into Firebug and then simply log a.__proto__

you will see that the prototype object will have haha, print, and constructor.
The object itself will have print2.

Thus the methods is being shared by all instances of Test.
Adding methods on the prototypes of objects in JavaScript is an efficient way
to conserve memory (as opposed to copying the methods on each object).

Hi-Jacking these functions on the fly

Prototypes are just objects that can be changed at runtime

Changing the method on the prototype of ‘a’ changes the result on ‘b’ as well.

This is because they share the same prototype and we are changing that object.

Again, prototypes are just objects that can be changed at runtime.

Oops, there is no going back, we have already modified the prototype for all instances of CircularList, now and in the future.

Remember, classes in JavaScript are not a blueprint like in other languages.
They just define objects that can be modified at will in runtime.

TO RECAP:

Inheritance

Continuing from our Test class example…

And OralText to extend from Text:

this is what it looks like diagram form:

So we start off with class Test. We declare function print2 inside the constructor, so its a property of the class. Every instance created from this class will have its own print2.

We then declare function print within the class, but outside of the constructor. print will be included in Test’s prototype object, which is simply represented as {}. This is because it derives (has __proto__ referencing) the default Object Prototype Object. There is no class name it derives from so its empty. Then, we directly attach the function haha to Test’s prototype object. Also, constructor is the special function that all instances of this class need to call before instantiation. Thus, that is why Test Prototype Object has haha, print, and constructor.


> Test.prototype

{haha: ƒ, constructor: ƒ, print: ƒ}
haha: ƒ ()
constructor: class Test
print ƒ print()
__proto__:Object

Then we have OralText, which extends from Test. It copies over the constructor properties, hence we get print2.

More importantly, this Test{} is independent from Test’s prototype object. OralText.prototype has a constructor property, which points back to OralTest. Thus, all instances created from OralTest will have OralTest as its type.

Another important thing is that OralTest.prototype is an object instantiated from Test.prototype. That’s why it has a __proto__ pointing to Test.prototype. This is so that we have a hierarchy in case instances of OralTest wants to access its parent’s prototype.


> OralTest.prototype

Test {constructor: ƒ}
constructor: class OralTest
__proto__: Object

As you can see OralTest’s prototype has a constructor pointing to OralTest (itself). This is so that all instances of OralTest will have OralTest as the type.
We also wee that the name of our prototype object is called Test This is because we extend from Test. Its __proto__ is referencing an Object. Let’s analyze this Object:


OralTest.prototype.__proto__

{haha: ƒ, constructor: ƒ, print: ƒ}
haha: ƒ ()
constructor: class Test
print: ƒ print()
__proto__: Object

So as we see, its the Test’s Prototype object with the haha and print functions.

So now
OralFinal.prototype will give a literal object with the name OralTest. Because our OralFinal extends from OralTest. You’ll see the special constructor function.

We are now at the lowest level of the hierarchy. We want to go up the hierarchy. So we follow the __proto__ path. You’ll see its __proto__ is that of Test. This is because OralFinal’s Prototype Object OralTest, is an object instantiated from Test.

OralTest {constructor: ƒ}
constructor :class OralFinal
__proto__: Test

If you go up one more __proto__, aka __proto__ of Test, you’ll see the no name Prototype Object with the functions haha, print, constructor.

Then if you go up one more, you’ll reach the default object Prototype object. That is the highest point.

  • Classes are NOT hoisted
  • Classes are first-class citizens
  • Classes are executed in strict mode

Another Example

Given class PersonCl:

Maps WeakMaps, Sets, WeakSets

https://javascript.info/map-set-weakmap-weakset

Map is a collection of keyed data items, just like an Object. But the main difference is that Map allows keys of any type.

The major difference of Map from JavaScript Object is; objects accept only String or Symbol key, but Map accepts anything.

Map can also use objects as keys.

For instance:

Iteration over Map
For looping over a map, there are 3 methods:

map.keys() – returns an iterable for keys,
map.values() – returns an iterable for values,
map.entries() – returns an iterable for entries [key, value], it’s used by default in for..of.

For instance:

https://www.mattzeunert.com/2017/01/31/weak-maps.html

todo

Set

A Set is a collection of values, where each value may occur only once.

Its main methods are:

new Set(iterable) – creates the set, optionally from an array of values (any iterable will do).
set.add(value) – adds a value, returns the set itself.
set.delete(value) – removes the value, returns true if value existed at the moment of the call, otherwise false.
set.has(value) – returns true if the value exists in the set, otherwise false.
set.clear() – removes everything from the set.
set.size – is the elements count.
For example, we have visitors coming, and we’d like to remember everyone. But repeated visits should not lead to duplicates. A visitor must be “counted” only once.

Set is just the right thing for that:

Private properties in es6 classes (js)

references:

  • https://stackoverflow.com/questions/22156326/private-properties-in-javascript-es6-classes
  • https://www.javascriptjanuary.com/blog/es6-classes
  • https://ttmm.io/tech/private-variables-in-javascript/
  • https://esdiscuss.org/topic/es6-problem-with-private-name-objects-syntax

ECMAScript 2015 (aka ES6) introduced classes to JavaScript.

Older versions of the language would allow you to define an object type directly using function constructors, but didn’t truly support object-oriented inheritance the way developers are used to.

Part of this is due to the fact that JavaScript is a prototypal language, not an object-oriented language. Or at least older versions weren’t.

ES6 gave us classes with proper constructors, methods, properties, and inheritance.

You could define a real class in ES6 and reuse it the same way you would a type in any other language:

The biggest unfortunate element of this class definition, though, is that there are no privacy modifiers.

The constructor, methods, and properties of a JS class are all public by default.

There’s no nature of a protected method or a private property. At all.

Module Privacy

The name variable inside this module is completely inaccessible to any code outside the module, yet it allows our class to keep track of this name property directly. This is exactly what we want, right?

Nope.

Since it’s outside the class definition, this variable is treated as a static property. Yes, it’s private to our module, but there’s only one copy available. If we make multiple instances of our Client above, we’ll overwrite name each time; the last instantiation will win and define the name used by all of the instances.

Hack

We create a static literal object called container. When an instance of Client is created, we give the instance an id, then use the instance id
to create a key in the container object. Its corresponding value would be an empty object where we store the name variable.

Thus, each instance at least can keep track of its own properties and usage.

Not attaching the new properties to the object, but keeping them inside a class constructor

Hiding with Weak Maps

https://javascript.info/map-set-weakmap-weakset
https://stackoverflow.com/questions/22156326/private-properties-in-javascript-es6-classes

WeakMaps associate data with Objects (here, instances) in such a way that it can only be accessed using that WeakMap. So, we use the scoped variables method to create a private WeakMap, then use that WeakMap to retrieve private data associated with this. This is faster than the scoped variables method because all your instances can share a single WeakMap, so you don’t need to recreate methods just to make them access their own WeakMaps.

WeakMap, another way

https://chrisrng.svbtle.com/using-weakmap-for-private-properties

WeakMap Technique
Traditionally, the way to have private properties in Javascript is to either prefix your variables or to encapsulate in a closure. Both of these methods do work, however they are either not restrictive enough (prefixes) or too restrictive (closures).

A WeakMap is similar to a HashMap but it allows objects as keys as well as not having a strong reference to its values (that’s why it’s called weak).

In the example below, we pass in an empty object into the WeakMap to hold all of the private properties of the class Wizard. To store the private properties, we also pass in the reference to the unique this object of the instance of the class Wizard as a key to the WeakMap.

When we actually run this code, you can see on the second line that when we try to access the property _private the class returned does not have reference to it because of the IIFE. However internal class methods can still change the values under _private. So you can only change the properties within the Class by using its accessor methods such as get and set. In doing so, keeping the namespace hidden from all functions except members of the class effectively implements private properties.

Break Down

ref – https://stackoverflow.com/questions/22156326/private-properties-in-javascript-es6-classes

The only truly private data in JavaScript is still scoped variables. You can’t have private properties in the sense of properties accessed internally the same way as public properties, but you can use scoped variables to store private data.

Scoped variables

The approach here is to use the scope of the constructor function, which is private, to store private data.

For methods to have access to this private data they must be created within the constructor as well, meaning you’re recreating them with every instance.

This is a performance and memory penalty, but some believe the penalty is acceptable. The penalty can be avoided for methods that do not need access to private data by adding them to the prototype as usual.

Example:

Scoped WeakMap

A WeakMap can be used to avoid the previous approach’s performance and memory penalty.

WeakMaps associate data with Objects (here, instances) in such a way that it can only be accessed using that WeakMap. So, we use the scoped variables method to create a private WeakMap, then use that WeakMap to retrieve private data associated with this. This is faster than the scoped variables method because all your instances can share a single WeakMap, so you don’t need to recreate methods just to make them access their own WeakMaps.

Example:

This example uses an Object to use one WeakMap for multiple private properties; you could also use multiple WeakMaps and use them like age.set(this, 20), or write a small wrapper and use it another way, like privateProps.set(this, ‘age’, 0).

The privacy of this approach could theoretically be breached by tampering with the global WeakMap object

Say you’re coding up a JS app and you import another file written by Fred for usage.
Then in your current file, you create your class and then use WeakMap to store your private variables.

index.js


output:
I am Private1 I am Private2

However, say Fred is a bit naughty and decide to overwrite the global object Weakmap like so:

base64Coder.js

So Fred decides to repoint the set reference in Weakmap’s prototype to his own custom function. But before doing so, in order not to lose the original function, he’ll retain it with a reference called oldSet.

He then has access to your key/values and can potentially change them, or even store them somewhere else. When he’s done, he’ll just return the original function, pointed to by referenceoldSet.

That said, all JavaScript can be broken by mangled globals. Our code is already built on the assumption that this isn’t happening.

Solution to fix this

In order to remedy this, you first declare references to the original set/get functions on the Weakmap prototype.
This ensures you have access to them. Now, when the tamperer decides to inject their own function, what they’re doing is re-pointing Weakmap.prototype.set to their own evil function as shown above. Thus, you don’t have to worry about that because you have already set your own reference to the correct original functions like so:

The way how it used is like so. The first object is the object you’re using to execute the function call. The next parameters get matched up with the function parmaeters.

Just make sure you do it at the top of your file before you import/require the questioning code components.

Half Answer – Scoped Symbols

A Symbol is a type of primitive value that can serve as a property name. You can use the scoped variable method to create a private Symbol, then store private data at this[mySymbol].

The privacy of this method can be breached using Object.getOwnPropertySymbols, but is somewhat awkward to do.

Example:

For example, this is how you would expose it:

Half-Answer: Underscores

The old default, just use a public property with an underscore prefix. Though not a private property in any way, this convention is prevalent enough that it does a good job communicating that readers should treat the property as private, which often gets the job done. In exchange for this lapse, we get an approach that’s easier to read, easier to type, and faster.

Example:

Decoupling JS apps using publisher subscriber pattern

http://dev.housetrip.com/2014/09/15/decoupling-javascript-apps-using-pub-sub-pattern/
https://gist.github.com/fatihacet/1290216

The problem

Let me use one of the most common features in modern web applications to introduce the problem: sending notification emails.

Let’s say we’re building an e-commerce site and we’d like to send a notification email to the customer when they make a purchase. A simple solution, and probably the most common one, could be something like this:

Notice how in sendEmail definition, it creates an instance of Mailer and calls function “sendPurchaseEmail”.
These two objects now have tight coupling because if you were to change sendPurchaseEmail to another name, you’ll have to do the same for sendEmail in Order. In other words, if you were to change the # of parameters, or the interface of the sendPurchaseEmail function, you’ll have to repeat those steps for sendEmail in Order.

Usually you know two components are coupled when a change to one requires a change in the other one, and that’s the case. If we want to change the name of the sendPurchaseEmail method or their params, we’ll have to change Order implementation as well. In a large application this bad practice means having a tightly coupled application where a small change can easily end up in a waterfall of changes.

What we want is Loose Coupling. Loose coupling is when you change the interface, but do not have to worry about changing it in all the other places that you have used it.

What is the Publish Subscribe Pattern?

In software architecture, publish–subscribe is a messaging pattern where senders of messages, called publishers, do not program the messages to be sent directly to specific receivers, called subscribers. Instead, published messages are characterized into classes, without knowledge of what, if any, subscribers there may be. Similarly, subscribers express interest in one or more classes, and only receive messages that are of interest, without knowledge of what, if any, publishers there are.

This pattern uses an event system that sits between the objects wishing to receive notifications (subscribers) and the objects firing the events (the publishers). This event system allows code to define application specific events which can pass arguments containing values needed by the subscriber. The goal is to avoid dependencies between the subscriber and the publisher.

Implementation

First, we declare a global literal object. This object takes will have the functionalities of publishing and subscribing.

It will be passed into an IIFE so that it has private block scope for its data structures.

then we create the data structures and variables needed for the implementation.

Say there’s a couple of topics: Badminton, Boxing, and Swimming.
First, we use the concept of key: value in order to keep track of them.
The key is the activity name “Badminton”, “Boxing”, “Swimming”.
We have a topics literal object that will store these keys.

TOPICS:

{
“Badminton” : [subscriber1, subscriber2, subscriber3….subscriber n]
“Boxing” : [{token: abcdefg, func : callback}… {token: 38fje8, func : callback}],
“Swimming” : [{token: a1b2c3d4, func : callback}… {token: 0fjdue7, func : callback}],

etc
}

Then for each key, we will have a literal object as the value.

That literal object has 2 properties:
– token
– func

token is simply an uid
func is the callback provided by the subscribers. Essentially, whenever something happens
and we want to publish something, we call this func, then pass in some data if needed.

“Badminton” : {token: a4456iol, func : callback}

Hence for each topic, we have an array of objects. Each of these objects have token and func properties. These objects represent
external objects that has subscribed to us and want to receive notifications when something happens.

Subscribe

Therefore, we create a public function property called subscribe. Its first parameter is topic, which is the topic that the external object
wants to subscribe to. For example, badminton, swimming…etc. The func, is the callback that we can use to notify that external object.

We must check to see if the topic exist. If there’s only data for say Badminton, and we subscribe to “swimming”, our pubsub system
will create an key/value entry for swimming and then create an empty array. This readies future external objects that wants to
subscribe to the topic “swimming”.

Then, we simply use a increment to simulate id generator. It is assigned to the subscriber. That way, each subscriber has an unique id to identify itself.

Finally, we create an object to store the token and the callback for the subscriber. We store this object into the array that corresponds to the topic that the subscriber wanted.

When we publish, we call execute this callback so that its owner will receive it.

Publish

So we have all these subscribers stored for different topics and now we’re ready to publish!

We create a public property for the pubsub. The first parameter topic represents the topic we want to publish for.
args is any published data you want to pass to the objects stored in arrays of different topics (subscribers).

First we check to see if there are any subscribers for the topic at hand. If say we have 3 subscribers for “Badminton”, and we try to publish something for “swimming”, we just spit out an error message because no such topic exist.

{
“Badminton” : [subscriber1, subscriber2, subscriber3]
}

Then we use a setTimeout to simulate internet activity.
First we get the array of subscribers by accessing the value by using topic as the index.

In an associative array, giving the topic key will give us the object value (array of subscribers).

Then we simply get the length of the subscribers.

By using the length, we use it to access the array of subscribers by using index. Remember, using strings in an associative array
will give you the object value associated with it.

By using numeric index, you’ll simply be giving the object value by index.

Hence after getting the length, we simply go through the subscriber array by looping through its index from length to 0, and
calling each subscriber’s callback. We can pass in whatever data we like for the publish.

Using the pubsub object

Unsubscribe

First, we go through all the topics available in our topics associative array.
For each of these topics, there is a list of subscribers.

For each element of the array subscribers, we check to see if the subscriber has the token.
If so, we remove that subscriber from the subscribers’ array.

FULL SOURCE

Constructor Pattern (js)

Before es6, JavaScript doesn’t support the concept of classes but it does support special constructor functions that work with objects.

By simply prefixing a call to a constructor function with the keyword “new”, we can tell JavaScript we would like the function to behave like a constructor and instantiate a new object with the members defined by that function.

Inside a constructor, the keyword this references the new object that’s being created. Revisiting object creation, a basic constructor may look as follows:

Constructors With Prototypes

Functions, like almost all objects in JavaScript, contain a “prototype” object. When we call a JavaScript constructor to create an object, all the properties of the constructor’s prototype are then made available to the new object. In this fashion, multiple Car objects can be created which access the same prototype. We can thus extend the original example as follows:

Above, a single instance of toString() will now be shared between all of the Car objects.

Circular List example

In the example below, we declare a ListNode constructor function so that we can instantiate objects from it,

We instantiate different ListNode objects and link them together in constructor function List. The linking happens because each ListNode has a next and previous.

List has 4 public properties:
– head
– tail
– now
– listName

Head, tail, now all point to different parts of the list.

The list uses prototype functions insert, remove, display so users can enter, remove, and display data from the list.
Thus, all instantiations of constructor function List use these prototype functions.

https://stackoverflow.com/questions/24488196/revealing-module-prototype-pattern

PRO – This saves a lot of memory because say we create 2 List instantiations called metro and gallery. There will be 2 copies of these functions for each instantiation. However, if we are to use prototype, there is only 1 instance of all these functions. And both metro and gallery will call that 1 instance.

In other words, the benefit of the prototype is that its properties are shared amongst all instances. This means that it’s static, not instance-specific.

CON – If you want to use the prototype, you cannot access truly private variables; you will need to use public properties

Modules (JS)

https://medium.freecodecamp.org/javascript-modules-a-beginner-s-guide-783f7d7a5fcc

Module is a standalone file that contains reusable pieces of code that encapsulates implementation details.

In other words, they are small building blocks that we put together to build complex applications.

Modules make it easy to abstract code. We use it to implement low level code. Other modules then import these abstractions and use them.

It does this through exporting values out of modules. If it needs other functionalities, it can import it from other modules.

These other modules are called dependencies.

Modules allow us to easily reuse code. If we need same functionalities, we just copy module to new projects.

As of es6, JS have a native module system.

1 module per file.

1) In modules, all variables are scoped only to the module. This offers a great way to encapsulate. The only way other modules can access data inside this module, it must import this module.

Whereas in a script, these variables would be considered to be global.

2) Module are executed in strict mode This means, the ‘this’ keyword is always undefined

In scripts, its sloppy mode and this references the global/window object.

3) Imports are hoisted. So no matter where you import, they are hoisted to the top.

4) In HTML, if we want to use a module, we must use

instead of the script way:

First we parse index.js
From the parsing we see that we need to import rand from math module. And showDice from the module.
We download and import all imported modules before execution. Module imports are synchronous.
Module downloads are asychronous.

We then link imports to math.js exports and dom.js exports.
Execute math.js and dom.js

Then finally, we can execute our index.js

Async/Await (syntactic sugar on top of Promises)

ref – https://www.toptal.com/javascript/asynchronous-javascript-async-await-tutorial

Promises paved the way to one of the coolest improvements in JavaScript. ECMAScript 2017 brought in syntactic sugar on top of Promises in JavaScript in the form of async and await statements.

Async

Declaring a function as async will ensure that it always returns a Promise so you don’t have to worry about that anymore.

The word “async” before a function means one simple thing: a function always returns a promise.

1st example

We can explicitly return a the static function for class Promise:

So, async ensures that the function returns a promise, wraps non-promises in it.

Await

The await operator is used to wait for a Promise.

It can only be used inside an async function.

The await expression causes async function execution to pause until a Promise is fulfilled, that is resolved or rejected, and to resume execution of the async function after fulfillment. When resumed, the value of the await expression is that of the fulfilled Promise.

The syntax:

The keyword await makes JavaScript wait until that promise settles and returns its result.

If there was no await, JS’s single thread will execute the async function, and down the main execution steps turn by turn. So that then end of your program will be executed even when your function is not done.

It won’t work because there is no await…

doubleAfter2Seconds returns Promise object. But since we don’t wait for it to resolve, the returned value is the Promise object. And not th resolved value that we want.


output:

running addAsync
trash.html:79 a: [object Promise]
trash.html:81 b: [object Promise]
trash.html:88 —–here—–
trash.html:89 [object Promise][object Promise]
trash.html:67 doubleAfter2Seconds: 4
trash.html:67 doubleAfter2Seconds: 6

As you can see, when your function is finally done, the result will be stranded. With nothing to execute the returned result.

Using await, it makes the JS thread wait until the promise is returned from the async function. Then proceeds to process it.


output:

running addAsync
trash.html:67 doubleAfter2Seconds: 4
trash.html:79 a: 4
trash.html:67 doubleAfter2Seconds: 6
trash.html:81 b: 6
trash.html:88 —–here—–
trash.html:89 10

In a more simple example:

await literally makes JavaScript wait until the promise settles, and then go on with the result.
That doesn’t cost any CPU resources, because the engine can do other jobs meanwhile: execute other scripts, handle events etc.
(JS only has 1 thread, which can skip around and execute different tasks, doing a little at a time)


output:
— begin —

Promise {: 3}__proto__:
Promise[[PromiseStatus]]: “resolved”
[[PromiseValue]]: 3

3

If you wish to await two or more promises in parallel, you must still use Promise.all.

Examples of using both

Asynchronous execution
Await is used inside of the async.

When we call a function with async, it

1) returns a Promise object
2) runs asynchronously

You can see this asynchronous activity going on because as the function f runs, the JS execution also continues
down and logs “grandma says:….come to dinner…!!….”.

using await and then at the same time

Whenever we deal with async functions, we must return a Promise. Thus we create a Promise, and make it run a setTimeout
function which is asynchronous. The setTimeout executes code after 3 seconds.

However, in our code, the Promise does not get returned right away due to the “await” statement. Rather, we must wait for the Promise to finish before moving on.
Therefore, the log statements and return Promise MUST wait for the Promise to resolve FIRST.
After the Promise resolves, we return the promise object.

Finally, because the promise object was already resolved, the
then() gets executed right away.

No Await

If we remove the await, the promise gets created, then since there is no “await”, we continue
with the log statements, and then returns the promise object.
Then the Promise executes the setTimeout, and resolves after 3 seconds.
What’s waiting for the resolve will be the then().

The execution will run in this order:

start of f()
create new Promise object
Wait for the Promise to resolve
here….
there….
everywhere…!!….
return the Promise object
waited 3 sec
1ST THEN:oh yea!

Another Example

Another example shows that await actually stops execution on the await line within that async function. While it waits, the JS execution will still move on
to execute after the async functionK

This is shown at 10, where the new Promise object has been created and will be returned. When it returns the Promise object, execution will need wait for the Promise to finish. Since the Promise takes 2 seconds, JS execution will continue after the async func onto line 11.

After the 2 seconds, we resolve the Promise at line 12. Then go on to 13, which we now have the passed in parameter value from the Promise’s resolve.

Whenever you “await” for a Promise, the rest of the async function will not run. Because it is “awaiting” your Promise to finish.
However, it will continue to execute the code that takes place AFTER the async function.

Take note at var x, it is awaiting a Promise to resolve inside of resolveAfter2Seconds…while it is waiting, execution continues at 11.

One more…!

Encapsulation in JS

ref – https://abdulapopoola.com/2013/03/30/static-and-instance-methods-in-javascript/

Creating React Components

https://www.kirupa.com/react/components.htm

Concept

This is terrible coding because you are doing a lot of repetitive coding.

thus, functions were created:

…and therefore, we can easily call the functions and provide parameters:

How it Works in React

Now, in React, say we want to render a bunch of h1. We have a index.html template with a given div for us to inject html content into like so:

Then, in index.js we use React’s API to render some custom html:

this repetitive usage of the h1s is the equivalent of writing the same code over and over again. Because what if we want to change them to h3. Or add bold to it. Its tiring to change it for everyone one of them. Conceptually, we want to do something similar to as how functions have solved repetitive code.

React Components

React components are reusable chunks of JavaScript that output (via JSX) HTML elements

This is where we use JSX to generate and render html to throw into a specific div. In our case, it would be the id=root div.

You create a class that extends the features of component. We do so like this:

This HelloWorld component is a component because it extends React.Component. If it didn’t do that, it would just be an empty class that doesn’t do much.

Inside our class, you can put all sorts of methods to further define what HelloWorld does.
However, there is mandatory function called Render which you must implement.

What we’ve done so far might seem crazy, but simply think of your component as a cool and new HTML tag whose functionality you fully have control over. This means you can do all sorts of HTML-ey things to it.

Properties

Our Hello component isn’t very useful because it only says Hello to one thing. It cannot say hello to other people/things. Say we want to have the Hello be applied to different names.

Just like with functions, you can pass in arguments that alter what your component does. There is a slight terminology update you need to be on top of. What we call arguments in the function world are going to be known as properties in the component world. Let’s see these properties in action!

Right now, our HelloWorld component is hard-coded to always send out Hello, world! as part of its return value. The first thing we are going to do is change that behavior by having return print out the value passed in by a property.

We are going to modify our HelloWorld component to allow you to specify who or what you greet besides the generic World.

Adding and accessing the property

We add the property by simply accessing it. If it doesn’t exist, it will be automatically added to the class. If it exists, it will access it.

The way you access a property is by referencing it via the this.props property that every component has access to. Notice how we specify this property. We place it inside curly brackets – { and }.

In JSX, if you want something to get evaluated as an expression, you need to wrap that something inside curly brackets. If you don’t do that, you’ll see the raw text this.props.greetings printed out.

Making the component call

Further example

Let’s make another component where we take an array, loop over it, and display the data. Define the component.
We add the nameArray property. Then we use the map function to look over each element in nameArray. We use parameter name and index to display the array data.

and we call the component like so:

output at localhost:3000:

Hello, Batman !!

0, Ricky
1, Vera
2, John
Hello, Superman !!

Source Code