Category Archives: javascript

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.

AVL tree

ref and source – https://github.com/redmacdev1988/avl-binary-tree

Balanced and UnBalanced Trees

height(left) – height(right) <= 1

  • Perfect tree – triangle. Height of every node is 0
  • Right skewed tree – nodes have right childs only
  • Left skewed tree – nodes have left childs only

It becomes a linked list and the run time back to O(n).

so…how should we add to BST so that it is more balanced?

AVL (Adelson-Velsky and Landis) is a special BST where it has self-balancing properties. There are other popular trees that also self-balances, such as red-black trees, 2-3 trees, b-trees…etc.

If distance > 1, use rotation to re-balance itself.

4 types of rotation:
Left (LL)
Right(RR)
Left-Right (LR)
Right-Left (RL

height and balance

The height of a node is the maximum number of vertices from the leaf to itself. Note thath height always start from the ground.

Thus, a leaf has a height of 0.

If the leaf has a parent node, the parent node’s height would be 1.

The balance factor of a node is the height of the left subtree minus the height of the right subtree.

  • If the result is > 0, the left subtree is larger
  • If the result is < 0, the right subtree is larger

In our example, we use absolute value as we don’t care which side is larger. We simply want to see what the balance factor is.

simple example

We have a root node 5, and its left node of value 2.

We calculate from the leaf. 2 is a leaf, so its height is 0. And in turn, balance factor is 0.
The left and right of a leaf is always null, thus, we don’t add 1.

At 5, the height is calculated as height of the subtree + 1. Thus, we get 1 for left subtree. And obviously 0 for right subtree. The height is the max of those 2 numbers. We get 1. The balance is the difference in the height of the left and right subtree, which is 1.

In the next example, it is the same, but simply flipped. The leaf has height of 0 because there is no left or right subtrees. Thus, its balance is also 0.
The root node 8’s left subtree is null, so its height is defaulted to 0.
Its right subtree exists so we add 1 to right subtree height (0), which results to 1.

Our balance is abs value of (left height – right height), which is abs(0-1) = 1.

In the last example, 50 is the root. Its left subtree is 10, which has height of 0, balance of 0.
Its right subtree is 80 which has height of 0, balance of 0.

Thus, at 50, its left height is 0 + 1. right height is 0 + 1, thus, max of left and right height is 1.
Its balance is therefore abs(1 – 1) = 0

Left Rotation

Right skewed trees are rebalanced by doing a Left Rotation.

Right Rotation

Left skewed trees are rebalanced by doing a Right Rotation.

Left Right Rotation

Left rotation on 5, so 7 comes up.

then we do a Right rotation, which makes 10 comes down.

And now, we are balanced.

Left Right Rotation

Height Calculations

After inserting new node into an AVL tree, we must re-calculate every node’s height.

code for UPDATE of height and balance

The code shows, if we’re at a subtree that is null, we don’t add 1. If there exists a subtree, we add 1 to the height of that subtree in order to get our current height.

We do this for both left and right.

The balance is simply the difference between the heights.

balanceFactor = height(L) – height(R)
> 1 => left heavy, perform right rotation
< -1 right heavy, perform left rotation

more examples

/ rotation

< rotation

> rotation

\ rotation

In order to fix it, we must do a left rotation.

Insertion with Balance

Removal of Node

Removal of Node is straightforward. We use public function remove and it uses utility traverseRemove function. travereRemove traverses the tree until it gets to the node with the value you want to remove.

When we find the node we’re looking for, it will look at 4 situations:

1) no children, simply delete and remove the current node
2) only the left child exist, so we return the node’s left subtree to be attached. remove the node
3) only the right child exist, so we return the node’s right subtree to be attached. remove the node.

4) both child exist.

This is the key in deletion. In this particular case, we want to return the leftmost of the right subtree or rightmost of the left subtree.
In our example, we return the leftmost of the rightsubtree.

ref – https://github.com/redmacdev1988/avl-binary-tree

Javascript Functions, scoping, and changing context

Since no inner function is declared, this function object is bound to the global scope.

In the above code:

  • global scope has one variable globalVariable.
  • However in globalFunction function object, notice notice we have a inner function, and thus, each function’s this scope is bound to itself.
  • the inner function cannot read the outer scope’s variable and thus both innerVariable and globalVariables are undefined.
  • In globalFunction’s globalVariable is undefined because it is not declared in its this scope

Thus, in the example, there are separate ‘this’ objects bound to each invoking function.

Unbeknownst to many Javascript developers, there is an arguments object created within a function. It is an Array-like object (only having the property length). Arguments has three main properties, namely, callee (the invoking method), length, and caller (the reference to invoked function).

Declaring a variable arguments inside a function replaces/overrides the primary arguments object.

Call, Apply

Both call and apply are used to invoke a method on an object.

Bind

The bind method is used to invoke methods while explicitly specifying this.

Sending file from html to node server (multer)

node server download

ref – https://dzone.com/articles/upload-files-or-images-to-server-using-nodejs

client side

Server side – index.js

Make sure you create the folder Images at the the directory your index.js is at.

However, our solution always jumps to another page.
In order to do it without any jump, we do it without a form

non-form way

First, we create a file uploader, and button control

For the button, whenever we press it, we will run function uploadImage
In this function, we first get the file object via the files property. The files property is an array, and we simply get the first element.

Once we have this file, we create a FormData object, append our file to it. Make sure to call it “imgUploader” as that’s what our multer code from the server side is expecting.

Assign the form data object to body and that’s it.

Javascript Prototype

https://javascript.info/prototype-inheritance

Prototype, function, and New

https://scotch.io/tutorials/better-javascript-with-es6-pt-ii-a-deep-dive-into-classes

When you call a function with new, four things happen under the hood:

  • A new object gets created (let’s call it O)
  • O gets linked to another object, called its prototype
  • The function’s this value is set to refer to O
  • The function implicitly returns O

We can also rewrite our Food function to work without the new keyword:

Everything is straightforward, except the setPrototypeOf.

Prototype Inheritance

Under normal circumstances, all objects in JavaScript — including Functions — are linked to another object, called its prototype.

If you request a property on an object that the object doesn’t have, JavaScript checks the object’s prototype for that property. In other words, if you ask for a property on an object that the object doesn’t have, it says: “I don’t know. Ask my prototype.”

This process — referring lookups for nonexistent properties to another object — is called delegation.

The output from our toString calls is utterly useless, but note that this snippet doesn’t raise a single ReferenceError!
That’s because, while neither joe or sara has a toString property, their prototype does.

When we look for sara.toString(), sara says, I don’t have a toString property. Ask my prototype.
JavaScript, obligingly, does as told, and asks Object.prototype if it has a toString property. Since it does, it hands Object.prototype’s toString back to our program, which executes it.

It doesn’t matter that sara didn’t have the property herself — we just delegated the lookup to the prototype.

In other words, we can access non-existent properties on an object as long as that object’s prototype does have those properties. We can take advantage of this by assigning properties and methods to an object’s prototype, so that we can use them as if they existed on the object itself.

Even better, if several objects share the same prototype — as is the case with joe and sara above — they can all access that prototype’s properties, immediately after we assign them, without our having to copy those properties or methods to each individual object.

This is what people generally refer to as prototypical/prototypal inheritance — if my object doesn’t have it, but my object’s prototype does, my object inherits the property.

In reality, there’s no “inheritance” going on, here.

In class-oriented languages, inheritance implies behavior is copied from a parent to a child.

In JavaScript, no such copying takes place — which is, in fact, one of the major benefits of prototypes over classes because we can dynamically switch to different prototypes and the prototype would “delegate” properties to those objects.

Setting an Object’s Prototype

The function, Object, has a property, called .prototype, which points to any object Object.prototype that you want.

The object, Object.prototype, has a property, called .constructor, which points to a function (Object). Keep in mind that this Object.prototype.constructor property is just a public property of Object.prototype. It is not used in any way in the construction of new objects or resolution of property names.

basic_prototype

You can also change the property to reference other objects. Rabbit.Property references an object. Any object created with new will now have their [[Prototype]] reference object {eats: true}. When we change Rabbit.Property to an empty object {}, further new objects created will then have their [[Prototype]] reference the new prototype object.

changing_properties

Prototype properties will over shadow objects that delegate from them

When both your object and its prototype has the same property, the prototype will have precedence.

Now we add the function “cook” to our prototype, in which we can then use.

Further Reading – Prototype Chain Details

In programming, we often want to take something and extend it.

In JavaScript, objects have a special hidden property [[Prototype]] (as named in the specification), that is either:
– null
– references another object. (all properties/methods of that object will be inherited)

That object is called “a prototype”:

When we want to read a property from object, and it’s missing, JavaScript automatically takes it from the prototype.

The property [[Prototype]] is internal and hidden, but there are many ways to set it.
One of them is to use __proto__, like this:

// So if animal has a lot of useful properties and methods,
// then they become automatically available in rabbit.
// Such properties are called “inherited”.

__proto__ IS NOT the same as [[Prototype]].

[[Prototype]]’s getter/setter is __proto__

If the subclass does not have the property/method, then JavaScript automatically takes it from the parent class.

Then, when console.log tries to read property rabbit.eats (**), it’s not exist in rabbit, so JavaScript follows the [[Prototype]] reference and finds it in animal (look from the bottom up).

Here we can say that animal is the prototype of rabbit or rabbit prototypally inherits from animal.

So if animal has a lot of useful properties and methods, then they become automatically available in rabbit. Such properties are called “inherited”.

Inherited Method

If we have a method in animal, it can be called on rabbit:

Longer Prototype Chain

getter setter in prototype inheritance

An interesting question may arise in the example above: what’s the value of this inside set fullName(value)?
Where the properties this.name and this.surname are written: user or admin?
The answer is simple: this is not affected by prototypes at all.
No matter where the method is found: in an object or its prototype. In a method call, this is always the object before the dot.
So, the setter actually uses admin as this, not user.

That is actually a super-important thing, because we may have a big object with many methods and inherit from it.
Then we can run its methods on inherited objects and they will modify the state of these objects, not the big one.

For instance, here animal represents a “method storage”, and rabbit makes use of it.
The call rabbit.sleep() sets this.isSleeping on the rabbit object:

If we had other objects like bird, snake etc inheriting from animal, they would also gain access to methods of animal. But this in each method would be the corresponding object, evaluated at the call-time (before dot), not animal. So when we write data into this, it is stored into these objects.

As a result, methods are shared, but the object state is not.

In JavaScript, all objects have a hidden [[Prototype]] property that’s either another object or null.

We can use obj.__proto__ to access it (there are other ways too, to be covered soon).

The object referenced by [[Prototype]] is called a “prototype”.

If we want to read a property of obj or call a method, and it doesn’t exist, then JavaScript tries to find it in the prototype list, from its immediate parent, and on up.

Write/delete operations work directly on the object, they don’t use the prototype (unless the property is actually a setter).

If we call obj.method(), and the method is taken from the prototype, the obj’s “this” still references the obj. So methods always work with the current object even if they are inherited.

Special

rabbit.jumps overrides its prototype reference’s jumps. Thus we get true.
Then we delete rabbit.jumps. This deletes the rabbit’s jumps (the one that overrides the prototype’s jumps).
Since the jump that overrides the prototype’s jump is now deleted, “rabbit.jumps” then refers to its prototype’s jumps, which comes out to be null.
We delete animal.jumps.
Since rabbit has no jumps, and then it goes to its prototype and sees no jumps, then jumps would be undefined, because undefined is assigned to anything that is undeclared.

Including Prototype, properties that describe the state of a particular object, is written into the object

Speedy derives from hamster.
lazy derives from hamster.
Stomach, since it is a property that describes the state of an object, is written into itself.
Thus, that’s why when Speedy calls stomach, it does this:

1) accesses this.stomach, stomach here belongs to hamster.
2) calls push on this.stomach. It pushes a string into array stomach.

When Lazy calls stomach, it does the same thing as above.

Thus, that’s when a parent class has a property that describes the state of an object, all its deriving objects will share that property.

In order to fix this you can do 2 things:

1)
Essentially, we work on “this”, the child object that is deriving.
Then, we create a new array with the food name, and references the child object’s property to it.

2) Instead of working on “this” in the parent object, we simply put all methods to be shared by “this” in the parent object, and leave the stomach property for its children like so:

__proto__ and prototype usage

http://sporto.github.io/blog/2013/02/22/a-plain-english-guide-to-javascript-prototypes/

new vs non-new object creation

http://code.tutsplus.com/tutorials/fully-understanding-the-codethiscode-keyword–net-21117

note:

The Global Object

When a function is called without an owner object, the value of this becomes the global object.

In a web browser the global object is the browser window.
This example returns the window object as the value of this:

standalone Function (notice no new!)

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.

new Object

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 anymore

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

We assign name attribute to the object cody.

Also, take note that the this properties are public because there is no closure. If we create a closure (by creating inner functions), then the properties attached to this will then be private.

Another example:

const object, changing attributes

http://stackoverflow.com/questions/30314457/how-to-make-function-parameter-constant-in-javascript

Const will only prevent re-assigning

It will not prevent modification of the attributes of the object.

For example, this will give you an error because you are trying to reassign the variable car to another object.

But if you were to change the attribute of the object, it is valid:


You’d see honda, white

http://stackoverflow.com/questions/30314457/how-to-make-function-parameter-constant-in-javascript

Another example:

However, bear in mind that const in ES6 notation does not make the variable immutable.

is a completely valid program and a will become [1, 2, 3]. const will only prevent you from reassigning a, so that you can’t do a = [] or a = {} or whatever once const a = [1, 2]; already defined (in that particular scope).

Read Only Variable

ref – http://stackoverflow.com/questions/2821509/can-you-use-constant-variables-in-javascript

if you’re looking for a read-only variable, you simulate that with something like

and then use it like

Installing JSLint in sublime

ref – https://github.com/devdoc/SublimeLinter-jslint
https://www.npmjs.com/package/nodelint

First, make sure you install the jslint npm package

npm install -g jslint

Install Package control

https://packagecontrol.io/installation

In your sublime, View > Console.
Then copy and paste this into the console and press enter:

Then after that, In Sublime,

Tools > Command Palette

type “Install” and type enter.
You will t hen see a menu popup with all the packages.

Look for SublimeLinter-jslint

Function Objects, and closures (javascript)

Function definitions

Use new to create instances, you are having objects returned to you.

Thus, the objects would be referenced by t1 and t2. If you were to access property name, you’d get the results:

t1 this.name – Test1() – hooray works!

public and private

this.property is public. var properties are private.

Given a function prototype without a closure, this.property is public, while a var is private

Here comes the Closure

Now, add the function definition growls into Test2.

By adding a function inside of a function, the whole thing becomes a closure.
2 things happen:

  • the inner function now has references to the local variables, such as any variables you declare
  • Outside cannot access the object’s properties. The properties have become private.

Hence, having our reference t2.name will give us undefined:

Because this is referenced differently in functions, depending on whether:

  • object that’s attached to the function, calls the function
  • scope calls the function
  • object uses addListener, attach…etc

CLOSURE EXPLAINED

A closure is when you have a function inside of a function. It automatically sets all properties to private.

Result

Test2() Constructor: Jabba the Hut
undefined yells out hadoken

The reason why this happens is because the this of Test2() and the this are different. The this in the growls function refers to the object that’s bound to the function.

The this of the Test2() is bound to its scope only, and does not affect the this of function growls. It can be used within Test2()’s function scope only and is used privately.

The this.name in the functions use the object that the function is attached to.

You can assign public attributes to the calling object by doing t2.name = “Ken”.

Hence

would give you


Test2() Constructor: Jabba the Hut
ricky yells out hadoken

because the this in function growls is referring to the object (in our case t2), which has attribute name of “ricky”.

Using var or let

If you were to use var or let, you can access the values because by definition, the var’s scope is the closest outer functional scope, and the let’s scope is the closest enclosing block scope.


Test2() Constructor: Jabba the Hut
ricky yells out hadoken
age is: 36
type is: human

read:

http://stackoverflow.com/questions/133973/how-does-this-keyword-work-within-a-javascript-object-literal

Using ‘self’ for non strict js

If you are not using strict mode, use self and use self in your inner functions in order to use properties like OOP.

result:


Test2() Constructor: Jabba the Hut
Jabba the Hut yells out hadoken
age is: 36
type is: human

The reason why it works is because self is a var, which means var’s scope extends all the way into the inner function’s scope as well.

NOT using New…our scope becomes global


Test2() Constructor: Jabba the Hut
Ryu.. yells out hadoken
age is: 36
global.name: Jabba the Hut

So as you can see because we are NOT using new, it means the attached this reference is the global object to our Test2 function.
this.name automatically attaches the attribute name to the global object.

We put object var t2 onto the stack, and assign Test2 function to this object t2.

t2.name = “Ryu…” basically assigns the attribute name to the t2 object.

t2 object then invokes the growls function. Inside the growls function, the this refers to the object that’s invoking it, which in our case, is t2. Hence, that’s why this.name will get “Ryu”.

Using “use strict” and “=>”

Until arrow functions, every new function defined its own this value (a new object in case of a constructor.

It is undefined in strict mode function calls, the context object if the function is called as an “object method”, etc.).

This proved to be annoying with an object-oriented style of programming.

So you’ll get

“Jabba the Hut yells out hadoken”
“Jabba the Hut yells out shoooo ryu ken!”

So what’s going on

We have to see how Test2 is created. We see that we use New to create it. So right away we know 2 things:

1) Test2 object’s this is lexically scoped to itself. The this used is private and lexically scoped within Test2 only.

2) On the stack we have a reference variable called t2. It now points to the object Test2 in the heap.

In growls function, the this in that function will refer to t2’s public attributes. Hence that’s why when you use this.name, it will be ‘Ryu’, because ryu is assigned to the public name attribute as defined for t2.

using self.name will give you “Jabba the Hut” because self references the this that’s privately scoped.

In growls2 function, due to using the arrow which gets the parent context, the this is lexically tied to the this that’s is used in Test2. IT DOES NOT TIE ‘THIS’ TO THE OBJECT THAT’S CALLING THIS FUNCTION ANYMORE’ Hence, typing the this to the private this of the object in the heap is more object oriented behavior. This is why its better to use arrow syntax.

Now, if the object was created like

It means Test2()’s this scope is tied to global, or window.

Thus, all the other behavior is the same. The only difference is that in Test2’s this.name, you are referring to the window or global object, and thus adding the name attribute to it.

If you go

you will see the result.