Category Archives: javascript

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

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/

Arrow functions (js)

ref – https://medium.com/@thejasonfile/es5-functions-vs-es6-fat-arrow-functions-864033baa1a
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
https://dmitripavlutin.com/when-not-to-use-arrow-functions-in-javascript/

When creating instances, every use of “new” defined its own ‘this’ value, where ‘this’ references the instance. The function defined in the constructor function will point to “this”. However, another function inside of that will not point to “this”.

Say we create a literal object and assign a reference named “Pets” to point to it.

The object has properties “names” and “owner”, and a description function. Let’s analyze how ‘this’ and the arrow functions affect each other.

In JavaScript, the method is a function stored in a property of an object. In our case, we have a function, and its stored in property “description”. When calling the method, “this” becomes the object that method “description” belongs to.

The “this” context in description is referencing the literal object that pets is pointing to. We see this when we log the ‘this’:


{ names: [ ‘baron’, ‘chief’, ‘axel’ ],
owner: ‘Ricky’,
description: [Function: description] }

We see the object displayed in the console.

Inside of our description function, let’s say we create another function and have a reference called innerFunc pointing to it. We then execute the reference to the function to call it. You’ll see that the ‘this’ inside of innerFunc is undefined.

The reason why is because the inner function does not have a owner, whereas function description does. Inner function see its surrounding scope as function description, and does not detect an object. Hence innerFunc’s this is undefined.

In a more general sense, the solution is that we need to set innerFunc (and our callbacks) up so that it refers to the ‘pets’ literal object.

output:

— description —
{ names: [ ‘baron’, ‘chief’, ‘axel’ ], owner: ‘Ricky’, description: [Function: description] }
— innerFunc —
undefined
— end of innerFunc —
— END OF description —

3 Workaround Solutions

Bind

We use the bind function to bind the pets this to our innerFunc.
Since our function innerFunc’s prototype is Object (as is with any compound objects in JS), we can use the bind function, and pass in the this. We do this inside of description function since description has the correct ‘this’ context.

Once bound, it returns a reference to the innerFunc with the correct this bound. We call that reference as a function and you’ll see that the “this” inside of innerFunc is valid.


— description —
{ names: [ ‘baron’, ‘chief’, ‘axel’ ],
owner: ‘Ricky’,
description: [Function: description] }
— innerFunc —
{ names: [ ‘baron’, ‘chief’, ‘axel’ ],
owner: ‘Ricky’,
description: [Function: description] }
— end of innerFunc —
— END OF description —

If you want multiple inner functions to work, you’ll have to repeat the binding of this object for each inner function.

Pass as a parameter

We can pass the this into the description function. Due to scope visibility, innerFunc will be able to see and use it.

Multiple inner functions will work also because the parameter is visible to them all.


— description —
{ names: [ ‘baron’, ‘chief’, ‘axel’ ],
owner: ‘Ricky’,
description: [Function: description] }
— innerFunc —
{ names: [ ‘baron’, ‘chief’, ‘axel’ ],
owner: ‘Ricky’,
description: [Function: description] }
— end of innerFunc —
— END OF description —

parent scope local var

Inside description function, we can push a reference called self onto the local stack, and have it point to the this object. Since self is at the parent scope of innerFunc, innerFunc sees self, and can use it.

Multiple inner functions will work because the scope of “self” is visible to them all.


output:

— description —
{ names: [ ‘baron’, ‘chief’, ‘axel’ ],
owner: ‘Ricky’,
description: [Function: description] }
— innerFunc —
{ names: [ ‘baron’, ‘chief’, ‘axel’ ],
owner: ‘Ricky’,
description: [Function: description] }
— end of innerFunc —
— END OF description —

Fat Arrow

An arrow function expression has a shorter syntax than a function expression and does not have its own this, arguments, super, or new.target. These function expressions are best suited for non-method functions, and they cannot be used as constructors.

An arrow function does not have its own “this”. The “this” value of the enclosing execution context is used. Thus, when using arrow functions inside of standard functions, the “this” within the arrow function will reference its enclosing function.

This works for multiple inner functions.

Arrow functions are best suited for non-method functions

..such as timer functions, array map functions, sync/async functions.
Any kind of functions used inside of calls should be used as arrow functions
because they can correctly find their outer scope’s this.

Arrow functions should not be used as method functions because for literal objects,
they cannot find the “this” to the literal object and will take the “global” this of
{} instead.

For example:

Arrow functions do not have their own this.

Arrow functions cannot be used as constructors and will throw an error when used with new.

Arrow functions do not have a prototype property.

Another Example

Another example is using globally defined functions like setInterval.
setInterval is a function defined in the global object Window and will be bound to that object.
Thus, whenever we call it, and try to use “this” in a function callback, the “this” will be referred to Window.
What we want is to make sure “this” refers to our Person object.

Thus, we have to use arrow function, because arrow function will get the “this” from its surrounding lexical scope.

Prototype and Inheritance in JS (non-class)

https://www.digitalocean.com/community/tutorials/understanding-prototypes-and-inheritance-in-javascript

note:

It is important to note that x.__proto__ is a legacy feature and should not be used in production code, and it is not present in every modern browser. However, we can use it throughout this article for demonstrative purposes.

Use Object.getPrototypeOf(x) instead.

Creating objects through Constructor Functions

Because each character will share many characteristics, such as having a name, and a level, we use a constructor functions to create templates for those common traits of each hero.

Every hero has a name, and a certain level of experience

We have created a constructor function called Hero with two parameters: name and level. Since every character will have a name and a level, it makes sense for each new character to have these properties.

The this keyword will refer to the new instance that is created, so setting this.name to the name parameter ensures the new object will have a name property set.

The hierarchy looks like this:

The Prototype Object

Whenever we create a constructor function, JS will automatically create a literal object that acts as the prototype object.

That literal object’s sole purpose is to contain functions and properties for all instantiations of your constructor functions.

Note that this object (like all objects of JS) derives from Object, and will have its __proto__ pointing to Object’s Prototype Object.

This literal object acts as the prototype object for Hero. It will also have a constructor property pointing back to your constructor function. Thus, making this prototype object the same type as your constructor function.

In our case, we create a constructor function “Hero” with its properties. JS gives us an empty literal object (Let’s call it Prototype Object) in order to act as a single object that keeps properties and functions that are shared among all instances of Hero.

Note that our Hero Prototype Object derives from Object and thus, has its __proto__ referencing Object‘s Prototype Object.

It then creates and assigns a “constructor” property from the Hero Prototype Object to your Hero constructor function. This makes the prototype object type Hero. Finally, it assigns the “prototype” property from your Hero constructor property onto the “Hero Prototype Object”.

Creating an Instance

What this means is that any instantiations of Hero will have its OWN properties and functions from the Constructor function.
hero1 is an instance we just created. It has its own properties of name and level, as indicated from the constructor function Hero.

hence if we were to make three hero objects, hero1, hero2, and hero3, they all have their own unique properties of name, and level.
i.e

hero1 is “Grom”, level 1
hero2 is “Haomarush”, level 2
hero3 is “Thrall”, level 8

In addition, they ALL share the “Hero Prototype object”.

So if the “Hero Prototype object” has a property “nickname” initiated to “Orc”, then they would all have nickname = “Orc”.

Same goes for any functions and other properties that “Hero Prototype Object” may have.

Let’s check on how this works. First we display the prototype of our object hero1. You can do it in 2 ways:


output:

Hero {}
Hero {}

Now repeat with hero2, hero3. You’ll see that their __proto__ all are Hero{}. They all point to the same Prototype Object Hero{}

Adding to the Prototype

Let’s add a property nickname to the prototoype, and see what it looks like:

Now our “Hero Prototype Object” will look like this:

Hero { nickname: ‘orc’ }

This means that when we try to read a property from a Hero object, say from hero1,
– it will try to look for “nickname” in the hero1 instance first.
– When it does not find it, it will go up the hierarchy (i.e hero1.__proto__) into the prototype object, which it will then find.
– If it still does not find it, it will keep going up the prototype chain, hero1.__proto__, hero1.__proto__.__proto__….etc

If you were to change nickname:

You cannot change it from the instantiation

Our hierarchy is like this.

We have our Hero instance, with its own properties of name and level. It has its __proto__ pointing to an object, with property “type”, which is
initialized to orc. It has its constructor back to Hero, and __proto__ references pointing to Object’s Prototype Object.

Simply put, don’t confuse yourself when you try to change a property or function of a prototype object.

You cannot change it through an instantiation like this:

Erroneously, many people may think that it will see if nickname exist in the instantiation, it does not. Then it goes up to the prototype and finds it there. Then it just assigns the new string.

When it comes to setting values, JS will only let you access at the prototype level. It only let’s you read at the object level if the property does not exist at the object level.

If you do decide to assign at the object level, essentially Javascript will interpret it as you wanting to add a property called “type” to your instance, and then initialize it.

Thus, in the hierarchy, you’ll get two property called “type”. One is at the instance level. One is at the prototype level.

If you want to set the prototype object to a new value, you must do so through Object.prototype.YourPropertyName.

Different character classes of heroes

However, each hero has different abilities. Some wield different weapons. All have vastly different skills and abilities.

It wouldn’t make sense to put all the abilities for every class into the Hero constructor, because different classes will have different abilities.

We want to create new constructor functions, but we also want them to be connected to the original Hero.

Let’s take a look at how we can accomplish this with prototype inheritance and constructors.

The Warrior

We use call in order to chain constructors. Essentially, call replaces a function’s this reference to a passed in object.
Hence, we replace Hero’s constructor function’s this reference to point to Warrior’s this. Then, any kind of initialization done in Hero will take place in Warrior. In other words:

  • We first create a constructor function called Warrior. This identifies Warrior.
  • We then pass the “this” reference to Hero via function call. Using Warrior’s “this” reference, we start to construct it like a Hero. Essentially, we are doing chain constructors for Warrior. We want to first initialize Warrior to be a Hero with Hero’s properties and functions.
  • Then, we come back to Warrior, and initialize Warrior’s properties.

note: The JavaScript call() Method

The call() method is a predefined JavaScript function method.

It can be used to invoke (call) a function with an owner object as the first argument (parameter).
In our example, instance person calls fullName. However, fullName’s this is myObject.

With call(), you can use a method belonging to another object.

This example calls the fullName function of person, but is using it on myObject:

…back to our example…

In the extended object Warrior, we initialize Warrior with Hero’s properties via javascript’s call function.

So in the same way, we call Hero’s constructor, but with Warrior’s this.
We pass Warrior’s this into Hero’ constructor

Warrior total properties = Warrior own properties + Hero properties;

We’ll add the attack() method to Warrior because its what they do. We want all instances of Warrior to be able to attack, as they should.

Linking up the Prototype

So the warrior class has properties of the Hero class. But what about the Hero’s functionalities? Let’s say the Hero’s prototype has functionality to be able to run, jump, and swim.

The warrior, being a hero, should automatically have those functionalities as well.

From javascript standpoint, when you create Warriors, it will be setup in a similar fashion like Hero. You’ll get a Warrior Prototype Object. Your Warrior’s prototype reference will point to Warrior Prototype Object. Warrior Prototype Object will add and point “constructor” back to your Warrior.

Since Hero’s prototype properties and methods are not automatically linked when you use call() to chain constructors, our Warrior will use Object.create() to link the prototypes.

Now, given Hero’s hierarchy is like so:

In order to inherit Hero prototype
1) Warrior will first disregard its own prototype object
2) Use Object.create to clone its own Hero Prototype Object.
3) re-point Warrior’s prototype to this clone.

Note:
The Object.create() method creates a new object, using an existing object to provide the newly created object’s __proto__

Object.create

w is simply a standalone object that has its __proto__ pointing to the Hero prototype object. It will be used as Warrior prototype object. But for now, let’s analyze this object:

Thus, as you can see, it does not have prototype property. It simply accesses all the functionalities of objA.


repoint Warrior’s prototype to our Hero Prototype Object clone

We simply want the type of all instances of Warrior to say Warrior {}.
It’s for clarity purposes.

We add an “attack function” to our custom Warrior Prototype Object.

We have class names’s prototype point to a literal object to denote that all
all instances of this class’s __proto__ should point to this literal object
for prototype functionalities. Since Warrior’s prototype now points to Hero Prototype object, this means all instances
of warriors have Hero Prototype Object’s prototype functionalities.

… given Hero Prototype functionality has jump, run, and swim, then our warrior will also be able to use these functionalities.

Now, all instances of Warrior can not only attack, but also jump, run, swim as well!

Double Prototype Level

Let’s create someone who has two types together.

First, we construct a Healer.

okay, so have Healer created. It derives from Hero in properties and prototype functionality.

double class power: Mage

Now let’s create a special class called Mage, where we can heal like a Healer, but also have our own Mage special ability.

Structure

You’ll see that an instance of the Mage will inherit properties and functions of its deriving object Warrior, and its deriving object Hero, and Object.

Furthermore, it will be able to use the whole hierarchy of its own prototype, which includes Warrior, Hero, and Object.


— Structure —

Mage {
name: ‘Thrall’,
level: 99,
weapon: ‘Ragnorak’,
special: ‘summons Bahamut’ }

Mage { constructor: [Function: Mage] }

Healer { constructor: [Function: Healer], heal: [Function] }

Hero { greet: [Function] }

{}

source code example

Accessing via Prototype Chain

Workout and Boxing example for JS prototype and class

Workout

First we have the Workout function class. Its declaration acts as the constructor.
We have three properties: title, datetime, and notes.

Setting the Prototype to a object literal

First, let’s define the function class Boxing. We will instantiate it, and pass it for Workout.prototype to point to.

set Workout’s prototype to a Boxing literal object

Now, the hierarchy looks like this:

All instantiation of Workout will share that literal object of type Boxing.

note:

The reason why we have a constructor property from var b is because var b (new Boxing) is the object for Workout Prototype. Thus, even though Workout is using a Boxing literal object to represent for its prototype functionality, its purpose is to be that of the Workout Prototype.

Thus, if we are to have a constructor property pointing back to Workout, any future instantiations of Workout will correctly show Workout, instead of Boxing.


output:

Workout {
price: 883,
coach: ‘Joel’,
friends: [ ‘Allen’, ‘Bundy’ ],
_display: [Function],
constructor: [Function: Workout] }
Workout {
title: ‘Monday Workouts’,
datetime: 2018-02-05T10:11:41.560Z,
notes: ’10x calisthentics’,
setNotes: [Function],
display: [Function] }

Getting property for object with prototype

Instantiate Workout and Get a property

1) Instantiate a Workout object. It basically creates an object from our definition of Workout.

2) Then let’s try using the setNotes function.

We pass in the string to newNote. In the function the ‘this’ evaluates to our Workout instantiation. We check to see if property ‘notes’ exist in Workout. It does, and we set it to our string.

We can log properties of Workout like so:


output:
boxing workout #38
2018-02-05T03:37:56.585Z
100 rounds of sparring

We then come back out to main. Since our prototype is set to Boxing object literal, let’s see what happens when we try to access property coach.

It displays the string “Joel”.

  • First, it will see if the property “coach” exists in the Workout object. It does not.
  • Because it does not, it will go to its prototype and check there.
  • The prototype object is Boxing. And Boxing does have “coach” property initiated to Joel.

Hence, “Joel” is displayed.

Keep in mind that all instantiations will share this Boxing object literal.
If we were to create another Workout object, it will display the same coach.


output:
boxinglesson1.coach: Joel
boxinglesson2.coach: Joel

Let’s evaluate the prototype to see what it looks like:


Boxing {
price: 883,
coach: ‘Joel’,
friends: [ ‘Allen’, ‘Bundy’ ],
_display: [Function] }

Let’s change the coach property to someone else:

Now, as you can see, we literally changed the prototype’s property to something “Rex”. And this gets reflected to other instantiations has their prototype property set to this object.


output:
Boxing {
price: 883,
coach: ‘Rex’,
friends: [ ‘Allen’, ‘Bundy’ ],
_display: [Function] }


boxinglesson1.coach: Rex
boxinglesson2.coach: Rex

code:

Calling prototype object’s functions

Let’s set the coach property back to Joel

Let’s look at prototype function _display

We must take heed that the this in the function belongs to the instantiated object, NOT the prototype. In our case, ‘this’ is an instantiation of Workout.

Thus, when we try to do something like this.coach, it will first check Workout object to see if it has a property called coach.

Because it does not, it will then go to the prototype and check for a coach property. In our case, it does.

Therefore, in our function, this.coach is valid (Joe) and thus, will display Joel in the function.

You will also notice we check if to see if this.display is a function. The this in question is the instantiation of Workout. Thus, we are asking Workout if it has a display function. It evaluate to true, and thus, we call Workout’s display function.

output
Boxing::_display() – display() function declared
— Workout::display(): boxing workout #38 —
@ approximately : Mon Feb 05 2018 11:43:48 GMT+0800 (CST), you will be doing:
100 rounds of sparring
Workout::display() – Your coach is: Joel
Workout::display() – Your price is: 883
————————–

Setting Properties for Objects with Prototype

When we were getting properties, JS first evaluates your instantiated object. Then if it doesn’t exist, it will go up to the prototype object. If it doesn’t exist there, then it will return undefined.

When we’re setting properties, its much more limited. Due to all instantiations share a common prototype object

we cannot set/change a prototype property through an instantiation of an object.

The only way to do is through accessing the prototype object itself like so:

Then, all instantiations of Workout will have prototype property coach “Katu”.

If you were to try to set a prototype property like this:

At first, you may think you have successfully set the prototype’s coach property.


output
—————-Boxing::_display()————–
Your cost: 883
You will be coached by: Sismundo
~~~ Boxing workout # 2 / 24
Boxing::_display() – display() function declared
— Workout::display(): boxing workout #12 —
@ approximately : Mon Feb 05 2018 11:58:22 GMT+0800 (CST), you will be doing:
Run 10 kms
Workout::display() – Your coach is: Sismundo
Workout::display() – Your price is: 883
————————–

But upon closer inspection, you’ll see that instantiations DO NOT allow you to set its prototype’s properties.

Instead, because you try to set a property that does not exist at the instantiation level, it will add the property for you. In our example, it added property coach to your Workout instantiation.

var, hoisting, and temporary deadzones (js)

ref – http://adripofjavascript.com/blog/drips/variable-and-function-hoisting.html
http://jsrocks.org/2015/01/temporal-dead-zone-tdz-demystified

Hoisting is about a variable or function definition (that’s being used or initialized) being available beforehand.

For example, if we declare and initialize a variable to a string, that variable is actually available beforehand at the very top. This is because the interpreter will get all the variables, and declare them at the very top first.

global, local scope variable over-rides

Function definition declaration

Function definition declarations are hoisted.

function definition hoisting only occurs for function declarations. In other words,
when you declare the function definition, then you can simply call it.

However, when the function definition is part of a function expression, then hoisting will not work.

For example, when we have a function expression variable that takes on the function definition, we cannot hoist the function expression variable.

Function definitions as part of function expression are not hoisted

If you have a function definition, and its part of a function expression, then you CANNOT do hoisting:

Class declarations ARE NOT hoisted

class declarations are not hoisted like function declarations.

For example, if you place the following code above the Animal class declaration section, you will get a ReferenceError:

Hoisting

var is function scoped. It is available in the whole function even before being declared

Declarations are hoisted. So you can use a variable before it has been declared.
Initializations are NOT hoisted. If you are using var, ALWAYS declare your variables at the top.

We declare x globally.

There is an if block, and in it, a var is declared with the same name.
that name gets hoisted to the top of the function. The name is the same
as the global one (x), and thus over-rides it.

es5

translates to:

In es6, when we use let, it works as expected:

let will hoist the variable to the top of the BLOCK (NOT top function like var)

Referencing the variable in the block before the variable declaration results in a ReferenceError

Temporal Dead Zone

“Temporal Dead Zone” is the zone from the start of the block until the variable is declared

Can you guess what console.log(x) will print now? Well, actually, the answer is nothing — the code above will throw a ReferenceError due to the TDZ semantics. That is because let/const declarations do hoist, but they throw errors when accessed before being initialized (instead of returning undefined as var would).

let and const declarations define variables that are scoped to the running execution context’s LexicalEnvironment.

In other words, the variables are created when their containing Lexical Environment is instantiated. This means whenever control flow enters a new scope (e.g. module, function or block scope), all the let/const bindings belonging to the given scope are instantiated before any code inside of the given scope is executed — in other words,

let/const declarations DO HOIST

…but may not be accessed in any way until the variable’s LexicalBinding is evaluated.

This is the Temporary Dead Zone

A given let/const-declared binding can’t be accessed in any way (read/write) until control flow has evaluated the declaration statement — that does not refer to the hoisting, but rather to where the declaration actually is in the code.

And the last part:

If a LexicalBinding in a let declaration does not have an Initializer the variable is assigned the value undefined when the LexicalBinding is evaluated.

This simply means that:

Is equivalent to:

Trying to access x in any way before control flow evaluates the initializer (or the “implicit” = undefined initializer) will result in a ReferenceError, while accessing it after the control flow has evaluated the declaration will work fine. i.e reading the x variable after the let x declaration in both samples above would return undefined.

Does the code execute without errors? What is the value of x after the code executes?

First off, remember that a let/const variable only counts as initialized after its initializer has been fully evaluated — that is, after the assignment’s right-hand side expression has been evaluated and its resulting value has been assigned to the declared variable.

In this case, the right-hand side expression tries to read the x variable, but x’s initializer has not been fully evaluated yet.

Thus, trying to read x at 2) results in a TDZ, and thus will throw a ReferenceError.

— in fact we are evaluating it at that point — so x still counts as uninitialized at that point and thus trying to read it throws a TDZ ReferenceError.

Other Examples

In the first line, the f() call makes control flow jump to and execute the f function, which in turn tries to read the b constant which, at this point in the runtime, is still uninitialized (in TDZ) and thus throws a ReferenceError. As you can see, TDZ semantics apply when trying to access variables from parent scopes as well.

Here, we have parameters a and b defined in the IIFE. Parameters are evaluated from left to right. At the left, we have a = 1.
Then the next parameter b takes on a, which at that time, evaluates to 1, thus b = 1.

The a, b are parameters. They are bound to the IIFE. thus, parameter b’s scope is in the IIFE. b gets hoisted. When a tries to assign b, it will throw a ReferenceError. Because b does not have a value yet.

more examples…

First we implement Numbers class with a simple constructor where we initialize

references, values in Javascript

There are no pointers in Javascript

In JavaScript, a variable may store two types of data:

  • primitive
  • reference

JavaScript provides six primitive types as undefined, null, boolean, number, string, and symbol.
Reference are Objects and Arrays.

When you assign a variable a value, the JavaScript engine must determine whether the value is a primitive or a reference value.

If the variable stores a primitive value, when you manipulate its value, you are working on the actual value stored in the variable. In other words, the variable that stores a primitive value is accessed by value.

Unlike the primitive value, when you manipulate an object, you are working on the reference to that object, rather than the actual object. In short, a variable that stores an object is accessed by reference.

Assign by primitive values

Another explanation

Assign by Reference

When you assign a reference value from one variable a to another variable b, the value stored in variable a is the address an actual object in the heap. That value is also copied into the location of the new variable b.

The address of the actual object stored in the heap is now stored in both variables a and b. As the result, both variables are pointing to the same object.

Thus, if you were to modify by accessing the properties of the object, it will change the object in the heap because you are essentially “dereferencing” it.

If your reference gets assigned to new value, it now points to a whole different object in the heap.

Create new Reference

When a variable is assigned to a new Compound Value (Object, Array), that variable points away and onto the new Compound Value.

Passed by Value

In JavaScript, all function arguments are always passed by value. It means that JavaScript copies values of the primitive variables that you pass to a function into local variables. Any changes that you make to the local variables inside the function does not affect the arguments that you passed in. In other words, the changes to the arguments are not reflected outside the function.

http://www.javascripttutorial.net/javascript-pass-by-value/

Compound values are Pass by value of the reference (function parameter passing)

When compound values (objects/arrays) are passed to functions, it passes the value of the reference. Simplest way is to just think of it as the parameter pointing to the compound object’s. Due to the parameter having the value of the reference of the compound value, if we access the property and change it, we are literally dereferencing the compound value, and changing it. Thus, the compound value will change.

If the parameter is assigned to something else, we are literally pointing it away to something. It will have the value of another reference.

Change original value in compound variable passed into a function

Compound variables are passed into a function via value of the reference. Hence, the only way it to literally wipe out its original values, then push new ones.

Reference a Compound Value

slice() creates your own array.
For primitives, it copies the values and each array has its own values.

But because we are dealing with objects, the array’s element will simply point the the object.

How to store a scalar primitive value through assign-by-reference?

Storing a scalar primitive through assign-by-reference is very simple. Just wrap a compound value outside of it and that’s it.
In our case, we put a primitive value inside of an object. Passed that object into a function, and change that value.

Arrays (js)

https://stackoverflow.com/questions/931872/what-s-the-difference-between-array-and-while-declaring-a-javascript-ar
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
https://medium.com/@gamshan001/javascript-deep-copy-for-array-and-object-97e3d4bc401a

Arrays are list-like objects whose prototype has methods to perform traversal and mutation operations. Neither the length of a JavaScript array nor the types of its elements are fixed. Since an array’s length can change at any time, and data can be stored at non-contiguous locations in the array, JavaScript arrays are not guaranteed to be dense; this depends on how the programmer chooses to use them. In general, these are convenient characteristics; but if these features are not desirable for your particular use, you might consider using typed arrays.

JavaScript arrays are zero-indexed: the first element of an array is at index 0, and the last element is at the index equal to the value of the array’s length property minus 1. Using an invalid index number returns undefined.

functions are all in Array.prototype

In your browser’s console, type Array.prototype and press Enter. You’ll be able to see all the functionalities used.

Create an Array

Access (index into) an Array item

Loop over an Array

Add to the end of an Array

Remove from the end of an Array

Remove from the front of an Array

Add to the front of an Array

Find the index of an item in the Array

Remove an item by index position

Remove items from an index position

Copy an Array

How to copy array

The slice() method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included). The original array will not be modified.

The code above creates clone of the original array; keep in mind that if objects exist in your array, the references are kept; i.e. the code above does not do a “deep” clone of the array contents.

…various ways

ref – https://www.briangonzalez.org/post/copying-array-javascript

There are many ways to copy an array in JavaScript, and with ES6, that list has grown even longer.

Here are some options I came up with (with the help of Twitter). They are shown in order of performance.

It is helpful to clearly distinguish an array index from an object property name.

All indexes are property names

but only property names that are integers between 0 and 2^32–1 are indexes

All arrays are objects, and you can create properties of any name on them.
If you use properties that are array indexes, however, arrays have the special
behavior of updating their length property as needed.

Note that you can index an array using numbers that are negative or that are not integers.
When you do this, the number is converted to a string, and that string is used as
the property name.

Since the name is not a non-negative integer, it is treated as a regular
object property, not an array index. Also, if you index an array with a string that happens
to be a non-negative integer, it behaves as an array index, not an object property.
The same is true if you use a floating-point number that is the same as an integer:

Another example:

output:

[ ‘ricky’,
‘bob’,
‘grandma’,
‘grandpa’,
‘shark’,
hobbies: ‘badminton, hill climbing, etc’,
lastName: ‘Tsao’,
‘-1.23’: ‘decimal’,
true: ‘DESTROY’,
false: ‘CREATE’ ]

5

The fact that array indexes are simply a special type of object property name means
that JavaScript arrays have no notion of an “out of bounds” error. When you try to
query a nonexistent property of any object, you don’t get an error, you simply get
undefined. This is just as true for arrays as it is for objects:

a = [true, false]; // This array has elements at indexes 0 and 1
a[2] // => undefined. No element at this index.
a[-1] // => undefined. No property with this name.

Array Literal


output:

BMW
undefined
[ ‘Saab’, ‘Volvo’, ‘BMW’, dealership: ‘longo, CA’ ]

What’s the real difference between declaring an array like this

var myArray = new Array();
vs
var myArray = [];

The difference between creating an array with the implicit array and the array constructor is subtle but important.

When you create an array using

You’re telling the interpreter to create a new runtime array (Array specs created at runtime). No extra processing necessary at all. Done.

If you use:

You’re telling the interpreter, I want to call the constructor “Array” and generate an object. It then looks up through your execution context to find the constructor to call, and calls it, creating your array.

If you do not redefine Array, then its not a problem. However, if someone decides to redefine it and implement the constructor, then everything goes haywire:

In other words, the difference is that using the new operator causes the interpreter to take all sorts of extra steps to go to the global scope, look for the constructor, call the constructor and assign the result… which in the majority case is going to be a a runtime array. You can avoid the overhead of looking for the global constructor by just using []. It may seem small, but when you’re shooting for near real-time performance in your app, it can make a difference.

other examples:

Performance Hit

https://jsperf.com/create-an-array-of-initial-size/2

Looks like creating literal array, using a while loop to initialize it, is the fastest among browsers.

For loop with push, is another good alternative

Deep Cloning

sort

if comparison is + (say, 100 – 40) do sort (if comparing 100, 40, it will sort to 40, 100)
if comparison is – (say, 40 – 100) DO NOT sort. leave as is.

So if we we get [100, 40]. 100 – 40 = 60. truthy, sort it. [40,100]
if we get [4, 20]. 4 – 20 = -16. falsey. don’t sort it. [4,20]

In the end, we get smallest to largest.

What if we want to sort largest to smallest?

so in comes [100(a),40(b)], we don’t want to sort in this situation and hope for a false.
So we say b-a. 40 – 100 = -60 don’t sort
in comes [40(a), 100(b)], we want to sort this, and try to give it a truthy. b-a, 100 – 40 = 60.

Now, we get largest to smallest.