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

The function slice gives variable zoom a new compound value to reference. Zoom is its own
compound value. If you were to push additional objects into cisco, you’ll see that they
have their own values.

However, keep in mind that the objects in the array given by slice are shallow.
The references in our array point to the same objects. They do not own their own.

For example, if you were to change object b’s skill, you’ll see that the changes are
reflected in both zoom and cisco.

output:

— zoom is shallow copy of cisco —
[ { name: ‘not entered’ }, { skill: ‘nothing’ } ]
[ { name: ‘not entered’ }, { skill: ‘nothing’ } ]

— cisco pushes c —
[ { name: ‘not entered’ },
{ skill: ‘nothing’ },
{ address: ‘nowhere’ } ]
[ { name: ‘not entered’ }, { skill: ‘nothing’ } ]

—–zooom—

[ { name: ‘not entered’ }, { skill: ‘javascript’ } ]

— cisco —

[ { name: ‘not entered’ },
{ skill: ‘javascript’ },
{ address: ‘nowhere’ } ]

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.

Why use Virtual (C++)

ref – https://stackoverflow.com/questions/2391679/why-do-we-need-virtual-functions-in-c?rq=1

Simple Over-riding

Without “virtual” you get “early binding”. Which implementation of the method is used gets
decided at compile time based on the type of the pointer that you call through.

OUTPUT:

Constructing Shape
Constructing Circle

Constructing Shape

SHAPE: Draw function
SHAPE: Draw function

Using Virtual

OUTPUT:

Constructing Shape
Constructing Circle

Constructing Shape

SHAPE: Draw function
Circle: draw function

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

getter setter (JS)

ref – https://javascriptplayground.com/es5-getters-setters/

this is ugly:

But this is ugly, and requires the users of your object to care that the properties are related; in a more complex example, that might not be as obvious as with names. Luckily, there’s a better way, added in ECMAScript 5.

we see that we have a get/set for property fullName.

Following them is the property they relate to (fullName) and a function body that defines the behavior when the property is accessed (name = person.fullName) or modified (person.fullName = ‘Some Name’).

In other words, get simply means to access the data, so we naturally return the property data. set means to set some properties in the object through one parameter. We can only provide one parameter because in an assignment, there’s only one parameter on the right side.

These two keywords define accessor functions: a getter and a setter for the fullName property.

When the property is accessed, the return value from the getter is used.

When a value is set, the setter is called and passed the value that was set. It’s up to you what you do with that value, but what is returned from the setter is the value that was passed in – so you don’t need to return anything.

The official way: Object.defineProperty

This method takes three arguments.

1) The first is the object to add the property to

2) the second is the name of the property

3) and the third is an object that describes the property (known as the property’s descriptor).

But why do it this way?

The advantage here isn’t immediately apparent. Other than being able to add properties after creating the initial object, is there a real benefit?

When you define a property this way, you can do much more than just define a setter or getter. You may also pass following keys:

configurable (false by default): if this is true, the property’s configuration will be modifiable in future.
enumerable (false by default): if true, the property will appear when looping over the object (for (var key in obj)).

We can also define properties that don’t have explicit getters or setters:

This will create person.age, and set it to the value 42. It’s important to note that this property isn’t writable. Calling person.age = 99 will have no effect. In this way you can create read-only properties. If a property has a value key set, it cannot have a getter or setter. Properties can have values or accessors, not both.

Not only that, but because the enumerable property defaults to false, this property will not appear when we loop over the object’s keys.

If we wanted to make a property writable, we would need to set the writable property:

Example 1


output:

10
7.071067811865475
7.071067811865475

Example 2

Example 3

Chaining Prototype

https://hackernoon.com/inheritance-in-javascript-21d2b82ffa6f

Example of chained prototype.

Hierarchy basics – Object

Firstly, all functions derive from “Object”, where “Object” is the default base of all javascript objects. The idea behind how hierarchy is laid out in JS is that the Object definition references an empty object called Object Prototype via a reference called “prototype”.

This Object Prototype object has a constructor reference pointing back to Object. Now all prototype objects of any function definitions you declare is an object literal. Since its an object literal, it will have a __proto__ reference, and this reference will be pointing to Object Prototype.

Example of custom Identification function

So let’s see how this works. Let’s declare a function definition called Identification. It automatically sets you up with a Identification object definition, and any related properties. In our case, we have a property called ‘name’, initialized to Ricky.

Furthermore, it will have a prototype reference to an empty literal object called “Identification Prototype”. This empty Identification Prototype will then have a constructor pointing back to our Identification object. More importantly, since this prototype object is a literal object, it will have a __proto__ reference pointing to Object Prototype.

If you were to simply create this code, and then evaluate the prototypes, constructors, and __proto__ references, you’ll see the output like so:

Identification.prototype references its own Identification Prototype object.
Identification.prototype –> Identification {}

The prototype object’s constructor references back to the Identification definition.
Identification.prototype.constructor –> [Function: Identification]

Since Identification.prototype is an object literal, it has a __proto__ and is pointing to Object Prototype.
Identification.prototype.__proto__ –> {}

Naturally, the constructor of the Object Prototype is a function of Object
Identification.prototype.__proto__.constructor –> [Function: Object]

Adding a function to Identification’s prototype

Appending any kind of functions to Identification prototype is straightforward. We are appending to the empty Identification Prototype object.

When we analyze Identification Prototype, we’ll see that the function has been added to it. As expected the constructor is still on Identification.

Identification.prototype –> Identification { getName: [Function] }
Identification.prototype.constructor –> [Function: Identification]

Person basics

In the same way Identification was created, let’s create a Person object.
When the Person function definition is created, it will automatically have a prototype reference to an empty object literal called “Person Prototype”. Person Prototype will have a constructor reference back to Person. Naturally, Person Prototype will have __proto__ pointing to Object Prototype.

As expected we have:

Person.prototype.constructor –> [Function: Person]
Person.prototype –> Person {}

With Identification and Person definitions, we now have a hierarchy like this:

Now, I want Person to prototype information from Identification because naturally, each person have some sort of identificaion. Prototypes can only reference objects, thus, let’s create an instantiation of Identification. We’ll have first and last name to “ricky Tee”.

Remember, any kind of object literal (or instantiation) will have their __proto__ pointing to their own Prototype.

So in our case, since we made an instantiation of Identification, our instantiation’s __proto__ will reference Identification Prototype (along with any appended properties and functions)
identificationInstance.__proto__ –> Identification { getName: [Function] }

We then check what constructor our __proto__ is pointing to. Naturally, it is Identification.

identificationInstance.__proto__.constructor –> [Function: Identification]

Accessing the reference constructor gives the same result. The reason why is because when we try to access “constructor” on the instantiation object, it does not find it. So it goes up the hierarchy to its __proto__ and tries to find it there. __proto__ is Identification Prototype, and here we find constructor pointing to Identification.
identificationInstance.constructor –> [Function: Identification]

Chaining Person to Identification

Finally, we are set to chain one prototype to the next.

Specifically, since we have an Identification object to chain to, we assign Person’s prototype reference to it.

As you can see from the picture, Person’ prototype points AWAY from Person Prototype and onto the Identification instance.

Let’s check out Person’s prototype and constructor references now:

Person.prototype –> Identification { firstName: ‘ricky’, lastName: ‘Tee’, friends: [] }
Person.constructor –> [Function: Identification]

As you can see, prototype references Identification. The reason why is because Person.prototype points to the instantiation of Identification. It has its standard Identification properties as you can see from the output.

Next, we try to access constructor in Person. There is no constructor property in Person, so it goes to prototype in order to find constructor. Its prototype is the instantiation of Identification and does NOT have constructor either. It then goes up the hierarchy 1 more level at __proto__, which points to Identification Prototype. At this point, it sees that the constructor references Identification. Thus, that is why Person.constructor is Identification.

Solution

After understanding the basics above, its obvious that all instantiations of Person will share the same Identification prototype. That’s not good. In order to have each Person instantiation have their own Identification, the solution is to Inherit properties. We do this by having Person’s constructor call on Identification’s constructor using ‘this’. That way, Identification can start appending properties to Person’s ‘this’. In other words, we let Identification get Person’s this, then add properties to it.

prototype, __proto__, object specifics, and sharing via prototype

https://hackernoon.com/prototypes-in-javascript-5bba2990e04b

Object.prototype is one of the rare objects that has no prototype: it does not inherit
any properties.

Step 1:

Every object in Javascript is derived from base Object. Base Object has many built-in properties, with its prototype pointing to an empty “Object prototype”. Hence, in memory we see “function Object” which has a prototype property referencing Object Prototype. Then it has a constructor reference coming back to Object.

Thus, when we create our literal object (with a name property in there), it derives from Object. Thus, it has its reference __proto__ pointing to Object Prototype.

That is why when you see an instance of Object (object literal) and Object, their prototype and constructor are the same.

Object.prototype –> {}
Object.prototype.constructor); –> [Function: Object]

objLiteral.__proto__ –> {}
objLiteral.__proto__.constructor –> [Function: Object]

Step 2 – Creating the Rabbit object

Now we create a Rabbit object. Therefore, by definition, Rabbit has a prototype reference pointing to an empty Rabbit Prototype. The Rabbit Prototype has a constructor pointing back to the Rabbit definition. But remember, every object in Javascript derives from Object. Hence Rabbit’s Prototype object is actually an object literal that has a __proto__ pointing to Object Prototype.

So as you see, Rabbit’s prototype and prototype.constructor is very straight forward. But it will be surprising to the reader that Rabbit.prototype has a __proto__ property. That is because Rabbit.prototype itself is an empty object literal. And like any object in JS, it derives from Object. Thus, that is why Rabbit.prototype.__proto__.constructor is [Function: Object].

Step 3 – Connecting the Rabbit object

So now, let’s connect the Rabbit’s prototype to some other object literal instead of the empty default one given to us. Say an object literal with property name, initialized to “not entered”. In memory it will looks like this:

As stated earlier, any object in JS has a __proto__ pointing to Object.prototype. Thus, the object literal we created also has this. When we connect our Rabbit.prototype to it, the Rabbit’s prototype takes on the object literal.


Rabbit.prototype –> { name: ‘not entered’ }
Rabbit.prototype.__proto__ –> {}
Rabbit.prototype.constructor –> [Function: Object]

An interesting thing to note here is that when evaluating Rabbit.prototype.constructor, since
Rabbit.prototype is { name: ‘not entered’ }, and we call constructor on it, it does not exist.
So what it does is that it tries to find property “constructor” on object’s __proto__, which is
Object.prototype. It exists (Object.prototye.constructor), and it points to [Function: Object].

Instantiations of Rabbit

Prototype Chain

From all the information presented above, all prototype objects (except Object.prototype) are normal objects that do have a prototype. All of the built-in constructors (and most user-defined constructors) have a prototype that inherits from Object.prototype.

For example, Date.prototype inherits properties from Object.prototype, so a Date object created by new Date() inherits properties from both Date.prototype and Object.prototype.

This linked series of prototype objects is known as a prototype chain.

The problem with Prototoypes

As prototype object is shared among all the objects created using the constructor function, it’s properties and methods are also shared among all the objects. If an object A modifies property of the prototype having primitive value, other objects will not be effected by this as A will create a property on its objects.

If you were to create many rabbit instances, and then change the property name in its __proto__, all other rabbits will be affected.

Solution – Combine Constructor/Prototype

We know 2 things:

  • Every object calls the constructor and thus, gets its own instance of the function definition, along with its own properties.
  • Modifying a Prototype property using one instance reflects the other instances also.

What we can do is to define all the object specific properties inside the constructor and all shared properties and methods inside the prototype as shown below:

Full Source to Rabbit example

OUTPUT

Rabbit {}
{}
[Function: Object]
[Function: Rabbit]
— object literal —
{}
[Function: Object]
———————-
{}
[Function: Object]
———————-
Rabbit.prototype = objLiteral
— Rabbit —
{ name: ‘not entered’ }
{}
[Function: Object]
———————-
{ name: ‘not entered’, copy: [Function] }
[Function: Object]
Rabbit Constructor
{ name: ‘not entered’, copy: [Function] }
[Function: Object]