All posts by admin

fetch POST, cors error

HTML

So we have an image loader input file type. We also have a button control.
The onclick event for the button calls our js function uploadImage.

Once

Node js server side

animate div

Js interview

https://career.guru99.com/top-85-javascript-interview-questions/

Problem

Answer

This will actually log “1 3 2”, since the “2” is on a setTimeout which will only execute, by this example, after two seconds. Your application does not hang waiting for the two seconds to finish. Instead it keeps executing the rest of the code and when the timeout is finished it returns to afterTwoSeconds.

Problem

Answer

Not only is this surprising, but what makes this particularly gnarly is that foo2() returns undefined without any error being thrown.

The reason for this has to do with the fact that semicolons are technically optional in JavaScript (although omitting them is generally really bad form). As a result, when the line containing the return statement (with nothing else on the line) is encountered in foo2(), a semicolon is automatically inserted immediately after the return statement.

No error is thrown since the remainder of the code is perfectly valid, even though it doesn’t ever get invoked or do anything (it is simply an unused code block that defines a property bar which is equal to the string “hello”).

This behavior also argues for following the convention of placing an opening curly brace at the end of a line in JavaScript, rather than on the beginning of a new line. As shown here, this becomes more than just a stylistic preference in JavaScript.

Problem

Solution

Problem

Solution

In the outer function, both this and self refer to myObject and therefore both can properly reference and access foo.

In the inner function, though, this no longer refers to myObject. As a result, this.foo is undefined in the inner function, whereas the reference to the local variable self remains in scope and is accessible there.

Problem

Solution

What is JavaScript?

JavaScript is a client-side as well as server side scripting language that can be inserted into HTML pages and is understood by web browsers. JavaScript is also an Object Oriented Programming language.

What are JavaScript Data Types?

Following are the JavaScript Data types:

Number
String
Boolean
Function
Object
Undefined

What is the use of isNaN function?
isNan function returns true if the argument is not a number otherwise it is false.

What is negative infinity?
Negative Infinity is a number in JavaScript which can be derived by dividing negative number by zero.

Is it possible to break JavaScript Code into several lines?

Breaking within a string statement can be done by the use of a backslash, ‘\’, at the end of the first line
Example:

What are undeclared and undefined variables?

Undeclared variables are those that do not exist in a program and are not declared. If the program tries to read the value of an undeclared variable, then a runtime error is encountered.

Undefined variables are those that are declared in the program but have not been given any value. If the program tries to read the value of an undefined variable, an undefined value is returned.

Uninitialized variables

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

missing parameters

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

unknown variables of objects

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

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

Write the code for adding new elements dynamically?

shellsort (js)

Shellsort is the same as insertion sort. Except that it uses a pass array to decide how many number of steps to jump.

In Insertion Sort, we always use 1 step. When we backtrack, we go back 1 step. But in Shellsort, we have an array, where we decide how many jumps to backtrack. This is called a “gap”. Of course in the very end, we’ll definitely have 1 step at the end.

In our example, we decide to use 5, 3, 1. What this means is that we will sort this via Insertion via passes where we jump 5 steps, then 3 steps, then 1 step. So for step 5, we start at index 5 of the array. Do the Insertion sort, but instead of using 1 step when going backwards, we use 5 steps.

first pass, 5 steps

We start off at index 5. Will process the insertion sort, and when we’re done, we go down the array 1 by 1.

The insertion sort itself will use 5 steps when sorting via

Everything else is processed the same way as Insertion Sort. We get the current valueToInsert. It needs to satisfy a few points:

1) is the index larger or equal to the gap index?
2) is the previous gapped element larger than the valueToInsert?

If so, we assign the previous gapped element to the current one.
If not, we just put the valueToInsert back to the current element.

Given the Insertion Code with the gap element like so:

The gap we use is 5. So we need to do an Insertion pass where the gap is 5.

We start index 5. The value at that index is 11. 11 is the value we need to check and find a proper place to insert.

The Insertion sort happens when we have j point to i.

1) j>= gap, 5 >= 5 ? yes
2) previous gapped element > valueToInsert, 6 > 11 ? NO

dataStore[5] = 11, we move down the array.

shellsort_pass5_1

The next index is 6. dataStore[6] is 8. The previous gapped element is dataStore[6-5] is 0

1) j >= gap, 6 >= 5? yes
2) previous gapped element > valueToInsert, 0 > 8, NO

dataStore[6] = 8, we move down the array

shellsort_pass5_2

The next index is 7. dataStore[7] is 0. Its previous gapped element dataStore[7-5] is 2.

1) j >= gap, 7 >= 5? yes
2) previous gapped element > valueToInsert, 2 > 0 yes

When both requirements is true, we exchange the element values. Basically storing the previous value into the current value. This is the because the previous value is larger than the current value.

We continue on the insertion sort by looking back at -gap elements. Namely, j-= gap. Hence our j is now at index 2, dataStore[2] = 2.
We check the requirements again:

1) j >= gap, 2 >= 5 NO

So we jump out of the loop and assign the valueToInsert at dataStore[2]. This perfectly switches the numbers at dataStore[2], and dataStore[7].

shellsort_pass5_3

We move onto the next index at 8. dataStore[8] is 5.
Previous gapped element is dataStore[8-5] = 9

1) j >= gap, 8 >= 5, yes
2) previous gapped element > valueToInsert, 9 > 5 yes

Hence we need to copy the previous element to the current one. We then backtrack gap steps into index 3

1) j >= gap, 3 >= 5, NO
therefore dataStore[3] = 5.

We keep going down the array.

shellsort_pass5_4

We process the last element at index 9, dataStore[9] is 4.

dataStore[9] is 4
dataStore[9-5] is 3

1) j>= gap, 9 >= 5
2) previous gapped element > valueToInsert, 3 > 4, NO.

So we jump out of the loop
dataStore[9] = 4

next gap pass, 3 steps

We start from beginning to end, and at index gap. We do the insertion sort with gap steps, however, we process each element down the array one by one.

index 3

Hence, our next pass involves gap 3. We start off at index 3.
We see that dataStore[3] is 9. valueToInsert = 9.
Previous gap element is dataStore[0] is 6.

is index 3 >= 3 yes
6 > 9 (valeToinsert) NO, move on to next index

shellsort_pass3_1

index 4

We now on index 4.
dataStore[4] = 3, valueToInsert = 3
dataStore[4-3] = 0

4 >= 3 yes
0 > 3 (valeToInsert) NO, move on to next index

index 5

We now on index 5.
dataStore[5] is 11, valueToInsert = 11
dataStore[5-3] is 2

5 >= 3 yes
2 > 11 (valeToInsert), NO, move on to next index

shellsort_pass3_2

index 6

We now on index 6.
dataStore[6] is 8 valueToInsert = 8
dataStore[6-3] is 9.

6 >= 3 yes
9 > 8(valeToInsert), we then copy over the value from the previous element to the current

Thus, dataStore[6] = 9.

We go back 1 gap step so now j is at index 3.
dataStore[3] is 9
dataStore[3-3] is 6

3 >= 3 yes
6 > 8 (valeToInsert), NO, we skip out. have current index j, dataStore[3] = 8 (valueToInsert)

move forward down the array

shellsort_pass3_3

index 7

We are now at index 7.
dataStore[7] is 0. valueToInsert is 0.
dataStore[7-3] is 3

7>=3 yes
3 > 0 yes

Let’s copy previous element to current so now
dataStore[7] is 3.

j moves a “gap” step back to index 4

dataStore[4] is 3
dataStore[1] is 0

4 >= 3, YES
0 > 0 NO

dataStore[4] is 0.

Move forward

shellsort_pass3_4

index 8

dataStore[8] is 5 (valueToInsert)
dataStore[8-3] is 11

8 >= 3 yes
11 > 5 yes

So we need to copy the previous value over to current.

dataStore[8] = 11

Go back 1 “gap” step to index 5

dataStore[5] is 11
dataStore[5-3] is 2

5 >= 3 yes
2 >= 5 (valueToInsert) NO

dataStore[5] = 5

move on…

shellsort_pass3_5

Index 9

Finally, we are index 9.

dataStore[9] is 4 (valueToInsert)
dataStore[9-3] is 8

9 >= 3 yes
8 > 4 yes

so we copy the previous gap element to current
dataStore[9] = 8

we go previous gap element to index 6

dataStore[6] is 8
dataStore[6-3] is 9

6 >= 3, YES
9 >= 4 (valueToInsert), YES

copy the previous gap element to current
dataStore[6] = 9

go back “gap” elements

dataStore[3] is 9
dataStore[0] is 6

3 >= 3, YES
6 > 4 (valueToInsert) YES

copy the previous gap element to current
dataStore[3] = 6

go back “gap” elements

index is now 0
0 >= 3 NO

so dataStore[0] = 4 (valueToInsert)

Done for gap 3 pass

shellsort_pass3_6

Full Source

Circular List in JS (prototype pattern, constructor pattern)

Prototype Pattern

– Using prototypes to create classes, all instances of that class will the same functions.

– Can’t have private utility functions. All properties and functionalities can be seen by caller.

Constructor Pattern with scoped private variables

By using scoped variables, we can have privacy, and can create get/set functionalities for public access.

However, not very practical as I will need to create get/set functions for all the private variables.
Then, using them in my functions can be awkward as assigning references must be dealt with using set functions.
And being assigned, we’ll have to call the get functions.

Immediately-Invoked Function Expression (iife)

https://www.kirupa.com/html5/immediately_invoked_function_expressions_iife.htm

function variation 1 – declare named function, then execute it

function variation 2 – anonymous function expression, execute it via reference

function variation 3 – Immediately Invoked Function Expression

say you have a function you want to execute like so:

…usually, you’ll have a variable name reference the function, then execute it. Or you give the function a name, and use that name for the execution as shown above.

You can also invoke a function like so:

What we just did is create a reference and point it to the return value of a function expression. Remember, a function without a name is a function expression. A function with a name is a function statement.

If you want to write function() as an expression itself, without a variable reference pointing to it, the compiler will give you an error.

It’s expecting it to be a function statement. It’s looking for a function name. In order to remedy this, you can use parentheses. Also, when you use parenthesis, JS assumes that the inside is an expression. We can create a function expression and immediately invoke it like so:

The general structure for creating an IIFE that takes arguments is as follows:

You can invoke it outside or inside the parentheses, doesn’t matter.

example:

What happens in memory

When the IIFE is immediately invoked, we have an execution context pushed onto the execution stack.
In its Creation Phase, it will put variables into memory.

In our example, greeting variable is put into memory and assigned undefined. By definition, any variable created within a certain execution context belongs there. In other words, the variable is local to the function which is was defined. Furthermore, a let variable is local to the block which it was defined.

Sa you want to manipulate the global variable. Simple, just pass it in.

This pattern makes it intentional for you to affect the global object. And not by accidental.

Review Scope real quick…

…you learned that JavaScript doesn’t have the concept of block scoping. It only has lexical scope.

This means that variables declared inside a block such as an if statement or loop will actually be accessible to the entire enclosing function:

As you can see in this example, the foo variable, despite being stuck inside the if statement, is accessible outside of it because your if is not a scopable block. This ability to have your “supposedly inner” variables promoted and accessible to the entire enclosing function is known as variable hoisting!

When do use an IIFE?

what is so different about an IIFE compared to a function you declare and call immediately like you have always done?

The main difference is that an IIFE leaves behind no evidence of its existence after it has run.

This is largely because IIFEs are anonymous functions that are nameless. This means you can’t track them by examining variables. Because the code you put inside an IIFE is actually inside a function, any variables you declare are local to that function.

IIFE provides you with a very simple way of running code fully inside its own bubble and then disappearing without a trace.

By taking advantage of the local scope IIFE’s create, you can selectively choose what to expose or what not to expose.

Here, we declare an object. However, property secretCode is exposed for public usage.

By taking advantage of the local scope IIFE’s create, you can selectively choose what to expose or what not to expose

This time around, you won’t be able to access secretCode. The reason is that the contents of secretCode are buried inside the IIFE and not accessible publicly.

Usage: To Avoid Polluting the Global Scope

Let’s say you’re implementing your own objects. You have different function interfaces like so…

rtScript.js

The problem is, when you import your file into projects, what if other implementations have the same names as well? It would lead to name collisions.

So in order to solve this problem, we want to hide these function interfaces and just expose a global variable name like so:

What this does is that it hides all the function interfaces and global variables used in your implementation.
All that’s exposed is the rtScript variable.

Hence others can use your implementation like so:

otherCode.js

Usage: capture surrounding state via Closure, and parameter passing

Given we have a function quotatious

It takes an array, and pushes a inner function onto it. Thus, it manipulates the references in quotes and points them to their own respective inner function. Even though the scope have not been created just yet, each inner function references its surround environment. Thus, they all reference the i from the loop and the array names.

In the outer scope, when we declare people to be an array with let’s say 4 elements, and pass it into quotatious, we will see that quotes array inside quotatious will have its references pointing to inner functions.

Each inner function will reference i as well as name.

Then quotes array will be returned by quotations function.
We then execute its element, which is a reference to the inner function.

When we execute the 0th element of peopleFunction, it will execute the inner function. The inner function will create scope, and reference i. But at this point, i is 5 because it shared among all the inner functions in quotatious.

Thus, names[5] returns undefined.

Solution

The trick is to create a shell that holds the correct i for each inner function.
Hence we create an IIFE first. the IIFE will take in the i as a parameter, and copy the value into the parameter index.

names is captured by closure, where as i is captured by parameter passing.

This is the key here. As different i gets passed into the IIFE, the i is kept as that value via the parameter index. Hence any inner function in the IIFE will always be able to reference index as that value.

So when we use quotes to execute the inner function, the inner function will be able to get its own referenced i.

Insertion Sort

http://www.geeksforgeeks.org/insertion-sort/

Insertion sort is a simple sorting algorithm that works the way we sort playing cards in our hands

Say we’re given a data set, 8 5 3 12 2

Option 1 – previous is larger

We start off the algorithm at index 1.
So we see 5 and store it in a temp variable.

There are 2 conditions we must satisfy:

1) Is the current index > 0 ? (1 > 0 ? yes )
2) Is the previous element is larger than our temp? 8 > 5, yes.

Both satisfies so we copy the previous element (8) to the current location where 5 is.

We move 1 step back and hit index 0.

We evaluate the 2 situations again:

1) 0 > 0, no. We stop.

If we reach index 0, that means we’ve reached the end, and we store 5 there.

We then move on to index 2 and continue processing in the same manner.

Option 2 – previous is smaller

If say we have 3 5 7.

We start off at index 1.
We see 5 and store it in a temp variable.

There are 2 conditions we must satisfy:

1) Is the current index > 0 ? (1 > 0 ? yes )
2) Is the previous element is larger than our temp? 3 > 5, no.

In this case, we don’t do anything move onto the next index 2.

This is the part where if the whole array is sorted, we only execute this comparison and then move on to the next index. Since the previous will always be smaller than the current, we simply stop and move on. Hence, the best case is O(n) because we do execute a comparison at every index once. We do this for every element and then stop.

Insertion sort takes the current number and go backwards to see where to insert it. We do this by comparing the previous element and seeing if its bigger than our valueToInsert. If it’s larger, push it down and we keep going. If it’s smaller, we stop and we insert our number. If we reach the end at index 0, we insert our number.

insertionsort_ex_a

Now we have 5 8 3 12 2.

We work our next pass which is index 2 with value 3.

We store 3 and start searching for the insertion point. We evaluate the 2 points:

1) is index > 0? 2 > 0, yes.
2) We look at the previous element 8. is 8 > 3? yes, so we move 8 to where 3 is.

Move backwards 1 step.

1) is index > 0? 1 > 0, yes.
2) Then we look at previous element 5, is 5 > 3? yes. so we move 5 to where 8 is.

1) is index > 0? 0 > 0, no. We’ve reached the end. Hence we put 3 at index 0.

This leaves us with 3 5 8 12 2.

insertionsort_ex_b

Then we work on value 12.

1) is index > 0? index 3 > 0, yes.
2) Previous element 8 > 12?
no. We stop, and move on.

Moving on…finally, our last value is 2. Apply the same as we did above and we’ll see that 2 will be inserted at the way in the beginning because it is smaller than the other numbers.

insertionsort_ex_c

full source

Time Complexity

The best case input is an array that is already sorted. In this case insertion sort has a linear running time (i.e., O(n)). During each iteration, the first remaining element of the input is only compared with the right-most element of the sorted subsection of the array.

The simplest worst case input is an array sorted in reverse order. The set of all worst case inputs consists of all arrays where each element is the smallest or second-smallest of the elements before it. In these cases every iteration of the inner loop will scan and shift the entire sorted subsection of the array before inserting the next element. This gives insertion sort a quadratic running time O(n^2).

The average case is also quadratic, which makes insertion sort impractical for sorting large arrays.

However, insertion sort is one of the fastest algorithms for sorting very small arrays, even faster than quicksort; indeed, good quicksort implementations use insertion sort for arrays smaller than a certain threshold, also when arising as subproblems; the exact threshold must be determined experimentally and depends on the machine, but is commonly around ten.