All posts by admin

Garbage Collection (js)

http://javascript.info/garbage-collection

Reachability

The main concept of memory management in JavaScript is reachability.

Simply put, reachable values are those that are accessible or usable somehow. They are guaranteed to be stored in memory.

There’s a base set of inherently reachable values, that cannot be deleted for obvious reasons.

For instance:

– Local variables and parameters of the current function.
– Variables and parameters for other functions on the current chain of nested calls.
– Global variables. (there are some other, internal ones as well)
– These values are called roots.

Any other value is considered reachable if it’s reachable from a root by a reference or by a chain of references.

For instance, if there’s an object in a local variable, and that object has a property referencing another object, that object is considered reachable. And those that it references are also reachable.

Here the arrow depicts an object reference. The global variable “user” references the object {name: “John”} (we’ll call it John for brevity). The “name” property of John stores a primitive, so it’s painted inside the object.

If the value of user is overwritten, the reference is lost:

Now John becomes unreachable. There’s no way to access it, no references to it. Garbage collector will junk the data and free the memory.

2 references

… the object is still reachable via admin global variable, so it’s in memory. If we overwrite admin too, then it can be removed.

Interlinked objects

Now a more complex example. The family:

First, let’s start from main. We have a family reference that points to the function marry. At this point know that marry‘s function data will all be pushed onto the local stack.

– return reference, not known yet
– param “man” reference, which points to the object with property name “John”
– param “woman” reference, which points to the object with property name “Ann”

garbage_collection_family_1

After the code runs through, and just before marry function pops, the snapshot looks like below. The function’s references have not been popped yet, and points to their relative objects:

garbage_collection_family_2

After the marry function pops, all its references will be removed.
Then, let’s say we decide to remove some references:

garbage_collection_family_3

Unreachable island

It is possible that the whole island of interlinked objects becomes unreachable and is removed from the memory.

The source object is the same as above. Then:

The in-memory picture becomes:

The root has unlinked, there’s no reference to it any more, so the whole island becomes unreachable and will be removed.

Internal algorithms

The basic garbage collection algorithm is called mark-and-sweep.

The following “garbage collection” steps are regularly performed:

– The garbage collector takes roots and ‘marks’ (remembers) them.
– Then it visits and “marks” all references from them.
– Then it visits marked objects and marks their references. All visited objects are remembered, so as not to visit the same object twice in the future.
– And so on until there are unvisited references (reachable from the roots).
All objects except marked ones are removed.

We can clearly see an “unreachable island” to the right side. Now let’s see how “mark-and-sweep” garbage collector deals with it.

The first step marks the roots:

The main things to know:

Garbage collection is performed automatically. We cannot force or prevent it.

Objects are retained in memory while they are reachable.

Being referenced is not the same as being reachable (from a root): a pack of interlinked objects can become unreachable as a whole.

f.prototype and constructor (js)

http://javascript.info/function-prototype

[DRAWING HERE]

In modern JavaScript we can set a prototype using __proto__.

But in the old times, there was another (and the only) way to set it: to use a “prototype” property of the constructor function.

It is known that, when “new F()” creates a new object…

the new object’s [[Prototype]] is set to F.prototype

In other words, if function F has a prototype property with a value of the object type, then the “new” operator uses it to set [[Prototype]] for the new object.

Setting Rabbit.prototype = animal literally states the following: “When a new Rabbit is created, assign its [[Prototype]] to animal”.

Constructor Property

As stated previous, we have the “prototype” property point to whatever object we want as the parent class to be inherited from future “new”-ed functions.

However, what is this “prototype” property before our assignment?
Every function has the “prototype” property even if we don’t supply it.

The default “prototype” property points to an object with the only property constructor that points back to the function itself.

You can check it like this:

Rabbit prototype by default

By default whatever objects created from “new Rabbit()” will inherit from Rabbit.
The instance ‘rabbit’ has constructor property which points to Rabbit.

We can use constructor property to create a new object using the same constructor as the existing one.

Like here:

Future manipulations of the prototype property

JavaScript itself does not ensure the right “constructor” value.

Yes, it exists in the default object that property prototype references, but that’s all. What happens with it later – is totally on us.

In this example, we see that we repointed the prototype to a totally different object. Thus, other instances of Rabbit, will be deriving from the object with property jumps: true.

The assumption that instances of Rabbit will have a ‘Rabbit’ constructor will then be false.

So, to keep the right “constructor” we can choose to add/remove properties to the default “prototype” instead of overwriting it as a whole:

Or you can reconstruct it yourself. Just make sure to include the constructor property and set it to your this object:

The only thing F.prototype does: it sets [[Prototype]] of new objects when “new F()” is called.

The value of F.prototype should be either an object or null: other values won’t work.

The “prototype” property only has such a special effect when is set to a constructor function, and invoked with new.

By default all functions have F.prototype = { constructor: F }, so we can get the constructor of an object by accessing its “constructor” property.

Gotchas

The assignment to Rabbit.prototype sets up [[Prototype]] for new objects. The new object ‘rabbit’ then points to Rabbit. The instance rabbit’s [[Prototype]] then is pointing to Rabbit’s default prototype object with its constructor property.

Then Rabbit’s prototype points to an empty object. However, rabbit’s [[Prototype]] already is referencing Rabbit’s default prototype object with its constructor property. Hence that’s why rabbit.eats is true.

Problem 1

solution: true

prototype_answer1

Problem 2

Solution: false

prototype_answer2

Problem 3

Solution:

All delete operations are applied directly to the object. Here delete rabbit.eats tries to remove eats property from rabbit, but it doesn’t have it. So the operation won’t have any effect.

prototype_answer3

Problem 4

Solution
prototype_answer4

Constructors (js)

https://javascript.info/constructor-new

The purpose of constructors is to implement reusable object creation code

Constructor functions technically are regular functions. There are two conventions though:

They are named with capital letter first.
They should be executed only with “new” operator.

Every function is an object, and when an object is created with “new”, it runs through the constructor.
1) The constructor then uses ‘this’ and assigns an empty object to it.
2) It will then add properties you specify onto “this”.
3) Finally, it returns this.

Constructors in Javascript is used to construct objects and can be called many times by any references.

However, constructors can also be created and called just once, and not be saved for later use.

DUAL SYNTAX: new.target

ref – http://chineseruleof8.com/code/index.php/2016/02/29/this-in-function/

Inside a function, we can check whether it was called with new or without it, using a special new.target property.
This can be used to allow both new and regular syntax to work the same. The reason why we care about “new” is because when we “new” a function, it creates an object out of it with its own “this”.

However, if we do not use “new”, the value of this becomes the global object.
In a web browser the global object is the browser window.

For example:

The reason why window.name logs Cody Lindley is because the ‘this’ inside the function references the window global object. Hence when we attach the attribute name to this, it attaches name to the window object. the ‘this’ has nothing to do with the object Person.

Now, when we use new Object, we create an object on the heap, and “this” in our function refers to that object. IT IS NOT connected to the (global or window) object.

Hence, when we log cody.name, it works because cody is that object in the heap. The this in the function, refers to cody.

In order to make sure the “new” is always applied so that we get some consistency, we can check for new.target to see if “new” was used to create the object. If not, then we need to force it by returning an object using new.

Return from Constructors

Usually, constructors do not have a return statement. Their task is to write all necessary stuff into this, and it automatically becomes the result.
But if there is a return statement, then the rule is simple:
If return is called with object, then it is returned instead of this.
If return is called with a primitive, it’s ignored.
In other words, return with an object returns that object, in all other cases this is returned.

Methods in Constructor

Having a method in a constructor means you add the method definition as a property to “this”. Once that happens,
after you construct an object, you are free to call that method.

Is it possible to create functions A and B such as new A()==new B()?

Yes, it’s possible.

If a function returns an object, then new returns it instead of this.

So thay can, for instance, return the same externally defined object obj:

null vs undefined (js)

https://stackoverflow.com/questions/801032/why-is-null-an-object-and-whats-the-difference-between-null-and-undefined

The difference between null and undefined is as follows:

undefined

undefined: used by JavaScript and means “no value”.

– Uninitialized variables
– missing parameters
– unknown variables have that value.

> var noValueYet;
> console.log(noValueYet);
undefined

> function foo(x) { console.log(x) }
> foo()
undefined

> var obj = {};
> console.log(obj.unknownProperty)
undefined

null

null: used by programmers to indicate “no value”, e.g. as a parameter to a function.
Examining a variable:

console.log(typeof unknownVariable === “undefined”); // true

var foo;
console.log(typeof foo === “undefined”); // true
console.log(foo === undefined); // true

var bar = null;
console.log(bar === null); // true

Stack and Heap

https://stackoverflow.com/questions/79923/what-and-where-are-the-stack-and-heap?rq=1

The stack is the memory set aside as scratch space for a thread of execution.

When a function is called, a block is reserved on the top of the stack for local variables, parameters, and some bookkeeping data.

When that function returns (finishes execution), the block becomes unused (all the variables gets popped) and can be used the next time a function is called.

The stack is always reserved in a LIFO (last in first out) order; the most recently reserved block is always the next block to be freed. This makes it really simple to keep track of the stack; freeing a block from the stack is nothing more than adjusting one pointer.

The heap is memory set aside for dynamic allocation. Unlike the stack, there’s no enforced pattern to the allocation and deallocation of blocks from the heap; you can allocate a block at any time and free it at any time. This makes it much more complex to keep track of which parts of the heap are allocated or free at any given time; there are many custom heap allocators available to tune heap performance for different usage patterns.

Each thread gets a stack, while there’s typically only one heap for the application (although it isn’t uncommon to have multiple heaps for different types of allocation).

The stack is attached to a thread, so when the thread exits the stack is reclaimed. The heap is typically allocated at application startup by the runtime, and is reclaimed when the application (technically process) exits.

The size of the stack is set when a thread is created. The size of the heap is set on application startup, but can grow as space is needed (the allocator requests more memory from the operating system).

The stack is faster because the access pattern makes it trivial to allocate and deallocate memory from it (a pointer/integer is simply incremented or decremented), while the heap has much more complex bookkeeping involved in an allocation or deallocation. Also, each byte in the stack tends to be reused very frequently which means it tends to be mapped to the processor’s cache, making it very fast.

Another performance hit for the heap is that the heap, being mostly a global resource, typically has to be multi-threading safe, i.e. each allocation and deallocation needs to be – typically – synchronized with “all” other heap accesses in the program.

Javascript memory allocation

https://stackoverflow.com/questions/2800463/how-variables-are-allocated-memory-in-javascript
https://stackoverflow.com/questions/1026495/does-javascript-have-a-memory-heap

When you call a function, amongst other things a variable environment for that call is created, which has something called a “variable object”.

The “variable object” has properties for the
– arguments to the function
– all local variables declared in the function
– and all functions declared within the function (along with a couple of other things)

When a closure survives the function returning (which can happen for several reasons), the variable object for that function call is retained in memory (heap) by the reference from the closure.

At first glance, that would suggest that the stack isn’t used for local variables; in fact, modern JavaScript engines are quite smart, and may (if it’s worthwhile) use the stack for locals that aren’t actually used by the closure. (Naturally, the stack is still used for keeping track of return addresses and such.)

Due to our function bar (which is a closure) uses and references c, if our function call ends and pops, our closure bar is still chained to “foo”, and thus be able to use c. Depending on the js engine, it may then move “c”

Javascript pass by reference or pass by value

https://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language?rq=1

Javascript parameters are pass by value, the value is that of the reference address.

obj1 is a reference that points to the object. Specifically, it points to the address of the object.
In the function changeStuff, its parameter ‘numParam’ is pushed as a reference on to the local function stack. It then copies by value the address of the object pointed to by obj1.

Parameter reference dereferences the object

Inside changeStuff, when we access the property item, our reference would dereference the object and get the value of item. Then assign it a new value “changed”. That’s why when the function finishes and pops, our obj1 reference outside will see that its property item was dereferenced and changed to “changed”.

js-pass-by-val-using-address

Simply points away

The other situation is that we assign our parameter reference to another object. When this happens, we point our reference away from the object that obj1 points to, and onto the new object. That’s why when our function exits, the obj1 still points to its own object and the item property is still “unchanged”

Primitives – Pass by Value

In JavaScript there are 5 primitive types: undefined , null , boolean , string and number. They are all passed by value.

Typing in javascript

https://stackoverflow.com/questions/964910/is-javascript-an-untyped-language

strong/weak can be thought of in relation to how the compiler, if applicable, handles typing.

Weakly typed means the compiler, if applicable, doesn’t enforce correct typing. Without implicit compiler interjection, the instruction will error during run-time.

“12345” * 1 === 12345 // string * number => number

Strongly typed means there is a compiler, and it wants you an explicit cast from string to integer.

(int) “12345” * 1 === 12345

In either case, some compiler’s features can implicitly alter the instruction during compile-time to do conversions for you, if it can determine that is the right thing to do.

Thus far, JavaScript can be categorized as Not-Strongly-Typed. That either means it’s weakly-typed or un-typed.

Arrow function (e6 js)

For arrow functions, this is picked up from surroundings (lexical).

In other words, Arrow functions are lexically scoped; this means that

their ‘this’ is bound to the context of the surrounding scope

That is to say, whatever ‘this’ refers to can be preserved by using an arrow function.


output:

Test2() Constructor: Jabba the Hut
Age is: 36
Ryu.. yells out tats makesen bukakyu
Jabba the Hut yells out shoooo ryu ken!

Closures (inner functions)

https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-closure-b2f0d2152b36

A closure is the local variables for a function – kept alive after the function has returned

In other words,

a closure is formed when an inner functions is made accessible outside of the function in which it was contained, so that it may be executed after the outer function has returned.


At which point it still has access to the local variables, parameters and inner function declarations of its outer function.

Those local variables, parameter and function declarations (initially) have the values that they had when the outer function returned and may be interacted with by the inner function.

1) We get the reference of the returned inner function.
2) Pass in a parameter so its inner function can grab onto it.
3) Execute the reference, which creates scope and grabs.

output:
Boooom! param is: 88

Now we do the same thing, but in a loop.

output:
Boooom! param is: 0
Boooom! param is: 1
Boooom! param is: 2

In an async situation, let’s say we have setTimeout that asks for a function to execute when a certain number of seconds have passed.

If we pass a function with a parameter (like what we have above), we’ll be able to have a closure and save state as well. We pass in one variable to the parameter, and the closure references that 1 parameter.

But because we do this in a callback, we must combine the 3 steps together.

So

1) We get the reference of the returned inner function.
2) Pass in a parameter so its inner function can grab onto it.
3) Execute the reference, which creates scope and grabs.

becomes an Immediately Invoked Function Expression:

therefore,

First it logs the callback function because we immediately execute it:
‘setTimeout: 88 √’

Then it returns the inner function. Due to the execution of the callback function, the inner function will create scope and reference parameter index from its local.

output:
After 2 seconds!…..inner func logs: 88

Async situation, in a loop:

We run an async operation where it executes a function after a second.
The inner function references it parameter, which is passed in via an Immediately Invoked Function Expression.

Under the hood, a closure is a stack-frame (which contains accessible variables), which has not been deallocated when the function returns. (as if a ‘stack-frame’ were malloc’ed instead of being on the stack!)

Closures are frequently used in JavaScript for object data privacy, in event handlers and callback functions, and in partial applications, currying, and other functional programming patterns.

What is a Closure?

A closure is the combination of a function enclosed with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function’s scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.

First, a simple Object with public and private properties

output:
blademaster.name – BladeMaster

Adding public function, and a Closure

To declare a closure, simply define a function inside another function. This is also called an inner function. Inner functions, are private scope by default. You can make it public for instances by assign public properties to it. In other words, you expose the function to be used.

If you assign a property to a function, you make it public and the instance can call it.
However, if its just the function, then it is used as private function for your class to use.

output:

Constructing Orc: BladeMaster
hands
This is an inner function

Using property variable in closure

After you define the closure, you can simply use the property name as is. i.e property ‘name’ in closure ‘growls’.

Using this.name in the closure vs this.name in the object

Closure has access to

  • its own scope
  • parent function’s scope
  • parent function’s parameters
  • DO NOT HAVE ACCESS to parent scope’s this because ‘this’ is inside of a function (either stand-alone or within another method) will always refer to the window/global object.


output:
Constructing Orc: BladeMaster
Toro: For the burning blade!
Toro
local
hands
BladeMaster
ERROR this is undefined

Public properties assigned to Inner Functions can access “this”

Notice that when we assign public properties on Inner Functions, we can access this.
However, a standard inner function (no public properties assigned to it) will not be able to have access to the parent scope’s this.


output:
The Masters
who’s playing in it!?
[ { name: ‘T. Woods’, age: 37 },
{ name: ‘P. Mickelson’, age: 43 } ]
1) own vars
123
hehe
2) outer function’s vars
888
outer limits
3) outer function’s parameter
merry xmas!
4) Inside closure: undefined
1) own vars
123
hehe
2) outer function’s vars
888
outer limits
3) outer function’s parameter
merry xmas!
4) Inside closure: [global object]

If we do want private inner function to access parent scope

see http://chineseruleof8.com/code/index.php/2018/02/07/arrow-functions-js/ for detailed explanation
of using 3 ways to how to use ‘this’ in inner functions:

Using parent scope variable
Using bind or call
Using arrow

More Example

First, we create the Person object. In the constructor declaration, we have a private property called pvtArray.
Any functions within our class Person can access it as a outer scope, global variable.

We have a public property called nickname. This property is accessed with this within our class Person.

However, there is a caveat.

Let’s say we declare a public function called displayInfo. It is considered a 1st layer function and can see the ‘this’ object.

Any functions within function displayInfo are considered (2nd and later) functions. These functions cannot see the ‘this’ object and any reference to this will result in undefined.

Thus, in Person, if you are to see the commented out setTimeout function, this.nickname will be undefined because ‘this’ references Timeout’s this. In Timeout, there is no property nickname.

As mentioned earlier, we can use any of the 3 ways to bind ‘this’ to the correct context: fat arrow, local stack ‘self’, or bind.

Now we are going to write a Boss class. This Boss class has a public function called peekOnRandomEmployee.

We declare a new Person in that function. Then directly call displayInfo on it.

displayInfo needs a anonymous function as a parameter for its callback. We declare a anonymous function and pass it in.
The point here is that our anonymous function is a 2nd and later level function. Thus, its ‘this’ reference is on Timeout.

If we are to use the fat arrow function, the ‘this’ will then be assigned to its parent context. Its parent context is the instance. Hence, our ‘this’ inside the callback will be assigned to the instance.

Boss example

Notice how it references outer function variables a and p. By definition, a function’s scope extends to all variables
and parameters declared by its surrounding parents. And of course any global variables as dictated by scope rules.