Day 25 : Become a self-taught blockchain developer with zero knowledge in 365 days
By: Ximena Han
Tags: Ethereum Blockchain, JavaScript, Array Methods, Arrays, Iterables

Day 25 : Become a self-taught blockchain developer with zero knowledge in 365 days Ximena Han Feb 20·14 min read

order 8: the fundamentals of Javascrpit (Technical aspect, Computer Science, Phase 1: a normal technican)

5.4 Arrays

What is array?

Array is the special data structures that stores ordered collection. It is not classified as the data type, and belongs to the object type. However, it is a bit different than the object.

Why we need array?

Like object, array stores plenties of elements. But we need array because the object is unable to store these elements in the order.

delaration of array

syntax 1: let arr = new Array(); syntax 2: let arr = []; //this one is used all the time

the use of array PART 1: “let arr = []” (syntax 1)

multiple elements in [] the elements are numbered and start with 0 get the element by the number in []

4. replace the element

(1) fruits[2] = ‘Pear’; // now [“Apple”, “Orange”, “Pear”]

5. add a new one

(1) fruits[3] = ‘Lemon’; // now [“Apple”, “Orange”, “Pear”, “Lemon”]

6. the length of the array (the length is the number of the elements)

(1) alert( fruits.length ); // 3

7. able to show the whole array

(1) alert( fruits ); // Apple,Orange,Plum

8. any data types can be the elements of the array

9. the trialing comma

(1) the last element may end with comma(just like the object)

(2) The “trailing comma” style makes it easier to insert/remove items, because all lines become alike.

the use of array PART 2: quene

the mothod for array the most common use two operations: push & swift

push appends an element to the end.

appends an element to the end. shift take away an element from the beginning, advancing the queue, so that the 2nd element becomes the 1st.

3. the use in reality: a queue of messages that need to be shown on-screen.

4. the order for the quene: FIFO(first-in-first-out)

5. THE USE CASE (shift/unshift is always for the beginning)

(1) shift: name.shift()

(2) unshift: name.unshift(the added item)

supports multiple items at once

the use of array PART 3: stack

the mothod for array stack is one of the data structure two operations:

push adds an element to the end.

adds an element to the end. pop takes an element from the end.

3. added or taken only from the end

4. the use in reality: A stack is usually illustrated as a pack of cards: new cards are added to the top or taken from the top

5. the order for the stack: LIFO(last-in-first-out). the lastet one is recirved first.

6. THE USE CASE

(1) pop: name.pop()

(2) push: name.push(the added item) //==fruit[the length of array]=the added item

support multiple items at once

the use of array PART 4: quene+stack

JAVASCRIPT ALLOWS THE DATA STRUCTURE OF QUENE AND STACK, WHICH IS ALSO CALLED DEQUE Methods push/pop run fast, while shift/unshift are slow.

(1) reason 1: For shift, after removing the item in the beginning, it's not done yet, it has to move each of the left item one by one. And then update the length of the array.

(2) reason2: For unshift, it is similiar to shift

(3) reason 3: For pop and push, they merely have to add/remove the item in the end, and then renew the length.

The intermal representation of array

arrray can be classied as object type, but what makes array special is in its internal, which is the storing of it. The engine tries to store it in the contiguous memory area. This is designed by its nature, to store the ordered collection. Hence, there are somes cases that misuse array, but technically they still work

case 1: Add a property like arr.test = 5 as if it were an object (if you want the funciton of an object just use{}.)

as if it were an object (if you want the funciton of an object just use{}.) case 2: non-continuous: add arr[0] and then arr[1000] ,and there is nothing between them.

and then ,and there is nothing between them. case 3: don't follow the order: fill the array in the reverse order, like arr[1000] , arr[999] and so on.

loops for array

method 1: old version

2. method 2: new version: for...of

(1) The for..of doesn’t give access to the number of the current element, just its value

3. method 3: for…in (just like objects)

(1) not recommeded

A. for..in iterates over all properties, not only the numeric ones, which is many cases, we don’t what them to be iterated.

B. The for..in loop is optimized for generic objects, not arrays, and thus is 10-100 times slower.

the flexible use of length of array

automatically updates when the change affects the length able to truncate the array by altering its length, which is irreversible.

3. clear the whole array //arr.length = 0;

syntax 2 to declare the array: new Array()

rarely used, too long rarely used, special feature:If new Array is called with a single argument which is a number

(1) creates an array without items (all the elements would become undefined)

(2) with the given length.

arrays in the array

the alert of array: string

array has its own implementation of toString, which is by nature the alert of array itself would return a comma-seperated string

implement only toString conversion, so here [] becomes an empty string, [1] becomes "1" and [1,2] becomes "1,2" .

equality chack for array

==: is the same as the object

Two objects are equal == only if they’re references to the same object.

only if they’re references to the same object. If one of the arguments of == is an object, and the other one is a primitive, then the object gets converted to primitive, as explained in the chapter Object to primitive conversion.

is an object, and the other one is a primitive, then the object gets converted to primitive, as explained in the chapter Object to primitive conversion. …With an exception of null and undefined that equal == each other and nothing else.

if we compare arrays with == , they are never the same, unless we compare two variables that reference exactly the same array.

[] wil trigger type conversion to primitive and become empy, which is null, and would then trigger boolean conversion

2. ===: coverts no type

→ don't use ==, or=== for array. Instead, compare them item-by-item in a loop or using iteration methods.

the methods for array part 1

quene: name.push(item) & name.pop() stack: name.shift() 7 name.unshift(item)

the methods for array part 2: splice

if we want to delete the array, just like obeject, we can use th syntax delete. But the problem is for unordered object we won't care for the order of the remaining ones. For array, the deleted one is deleted off course, but the length remains the same. It is becuase the space for the deleted one is still there, and the left elements won't fill the empty space. However, this we what we usually want. The arr.splice method arr.splice(the first deleting item to count from indicating the position , how many items) //delete things in the required position and the rest would fill the hole up advanced 1: arr.splice(the first deleting item to count from indicating the position , how many items, "the 1 thing to fill up the space", "the secomd thing to fill up the space") //the new element can be open, it can even be aa number advaned 2: arr.splice(the first deleting item to count from indicating the position , 0, “the 1 thing to fill up the space”, “the secomd thing to fill up the space”) //insert items without removal advaned 3: arr.splice(-1 , 0, “the 1 thing to fill up the space”, “the secomd thing to fill up the space”) //negative indexes are allowed, -1 means one step from the end

the methods for array part 2: slice

get the required elements(subarrays) of the array arr.slice([start], [end])

3. if the end is not mentioned it would be the end of the array automatically

4. create the total copy

the methods for array part 3: concat

copy old items in the array, and add some new items(or copy the other data), which combine and become a new array it is just temporary, the change won't be stored the new items can be any elements, even the array is available objects can be added

special Symbol.isConcatSpreadable property make objects considered as an array

the methods for array part 4: forEach

iterate: run a function for every element of the array. The result of the function is thrown away and ignored.

example 1

example 2

example 3(a good use)

the methods for array part 5: searching in array part 1: normal search

the method 1 & 2 use === comparison

method1 : arr.indexOf(item, from) – looks for item starting from index from , and returns the index where it was found, otherwise -1 . method 2: arr.lastIndexOf(item, from) – same, but looks for from right to left. method 3: arr.includes(item, from) – looks for item starting from index from , returns true if found.

the methods for array part 6: searching in array part 2: advanced search

find an object with specific condition among the array of objects

1. method 1: find

name.find(function(item, index, array) looks for a single (first) element that makes the function return true . If it returns true , the search is stopped, the item is returned. If nothing found, undefined is returned. the function item => item.id == 1 with one argument is the most usage of this function

2. method 2: filter

Unlike find, the result of filter is an array of the matching elements

the methods for array part 7: transform the array in the way we want

arr.map(function(item, index, array) the often used method

transform each element into its length

the methods for array part 8: reorder the array part 1

change the order of the array the array itself is modified the normal sorting rule for numbers: The items are sorted as strings by default. the changed sorting rule for numbers : apply the self-defined function

5. other functions for the comparison

simple one for greater and less comparison

make good use fo arrow function

Use localeCompare for strings

the methods for array part 9: reorder the array part 2

reserve the order of elements arr.reverse();

the methods for array part 10: spilt the array easily

use case 1

use case 2, rarely used, a limit on the array length.

use case 3(spilt into letters)

the methods for array part 11: glue the array easily

arr.join(‘;’)

the methods for array part 12: caculate the whole elements of the array

The function is applied to all array elements one after another and “carries on” its result to the next call.

2. carry the current result and pass it to the next until the whole procedure is done

The function passed to reduce uses only 2 arguments, that’s typically enough. And 0 of the last argument is the initial value, which can be moved

3. the process

(1) On the first run, sum is the initial value (the last argument of reduce ), equals 0 , and current is the first array element, equals 1 . So the function result is 1 .

(2)On the second run, sum = 1 , we add the second array element ( 2 ) to it and return.

(3)On the 3rd run, sum = 3 and we add one more element to it, and so on…

4. The method arr.reduceRight does the same, but goes from right to left.

the methods for array part 13: the judgement of being an array

typeof won't work because array is kind of the object It returns true if the value is an array, and false otherwise. Array.isArray(value)

the parameters of the methods above: thisArg

rarely used The value of thisArg parameter becomes this for func the full syntax of methods

5.6 Iterables

the iterable for object: Symbol.iterator

arrays are iterable off course, and if we to make the object iterable, we have to achieve it by some tricks, which is the method named Symbol.iterator steps

(1) create an object that is not an array, but is already suitable for for..of

(2) use Symbol.iterator

(3) ask for next value

(4) ask the next to return value as an object

example 1

example 2 (shorter version, but can't use for...of more than once)

3. problem alert: Infinite iterators

(1) the loop might be endless, but ir can be stopped with break

the iterable for strings

Arrays and strings are most widely used built-in iterables

loop for string

for more complex composition

Calling an iterator explicitly

direct calls rarely needed more control for iteration

the difference between iterables and array-like

iterables are the datas using symbol.iterator method array-like are the datas with indexes and length

3. example

string: both iterable( for..of works on them) and array-like( for..of works on them) But an iterable may be not array-like. And vice versa an array-like may be not iterable. an object may have one of them or both

make iterables/array-like into an array

Array.from(the name of the target) use case 1:

(1) takes the object, examines it for being an iterable or array-like, then makes a new array and copies all items to it.

use case 1

3. use case 2

(1) The optional second argument mapFn can be a function that will be applied to each element before adding it to the array, and thisArg allows us to set this for it.

use case 2 ( provide an optional “mapping” function)

#

###Here is the problem, I've got a little impatience for the time spent on these concepts without knowing what they can be done. There are many of the concepts and they are getting more difficult for me fully grasp, especially for today's part, array itself and iterables are not easy to understand than the ones before. I have no idea it's due to the difficulties of the topic or the decreasing quality of the tutorial. My guess is both.

Anyway, it means that the degree of completion of each coming topics can no longer be the same as the previous one. It would be a big probelm. And here's the solution.

First, I have to lower expectations for the required time for learning this part. It would take much time than I thought previously. Second, I have to spend at least one day to clarify three things. The relationship beween javascript and node.js, the relationship between node.js and blockchain, especially ethereum, what would the completion of the learning of javascript which implements in node.js and then functions the application of blockchain look like.

In brief, I must have more understanding and clear imagination about the final outcome in order to comprehend the process of this learning is for, and thus helping the learning process to become more purpose-driven and focused. ###

order (4): Introduction to the blockchain technology by Ethereum, developer perspective

redo of this part:

the concept blockchain

We can just seperate the concept of blockchain into "block" and "chain". The block refers to the data struture that we store the datas in the network,and the chain means that all the blocks are connected together becoming the long chain, and this the connected chain itself is hard to tamper with. It is because all the new connected blocks contain the data of the previous of which becomes unbreakable.

What is Dapp

It is the app build on the decentralized network, Its basic composition is backend code, which runs on the p2p and decentralized network, predefined smart contract also in the network, and the front-end codes which can be strored in the personal or decentralized server.

The smart contract in Dapp

The smart contract in Dapp is transparent and accessible for everyone like open APIs. It's ok to copy others contract. Also, they can not be changed once being deployed to the network, so the testing of the contract must be exceptionally careful.

The shortcoming of Dapp

First, the maintenance problem. It is nearly impossible to maintain the code because it is deployed in the decentralized network. Second, the performance problem. In order to achieve the full security and the functional decentralization, the computational power cost is considerable compared to the normal one. Third, the cogestion problem. The entire network is only able to congest limited transaction per second, and if the transactions being sent exceed the limit of the network, the transaction fee would be considerable or the waiting time would be pretty long. Neither of them is a good thing. The user experience problem, the security extent the network hopes to achieve would surly lower the user experience, but the tools are emerging to solve this problem. The last is centraliztion problem. It's highlt possible that the Dapp isn't fully decentralized at all. After all, every app have different amouts of the codes running on the centralized server.

The two types of the account

There are two types of the account. The first is exterally-owned account, it is the one for normal users, it's free to create one, and the account can initiate the transaction. The other is the contract account. Its creation is the creation of the smart contract, which requires using the network storage and thus cost ETH. Also, it can not initiate the transaction actively, the trascation will be called when certain condition is fulfilled.

The creation of the account

First, it would give you the private key of the account. And then the public key is generated using specific method. Next, the account address is created using part of the public key.

What's in an account

An account has four fields. The first is nonce. It is quite different than the one in the block. The nonce of the account in for indicating the number of the transaction send from the account, just showing some information of the account. The second is balance, showing the balance of the account. The third is codeHash. It merely cotains some code fragements that are hashed. The last is storageRoot, it is the hash of the root of the merkle tree that encodes the storage contents of the account.

The difference between the address and the wallet

They are quite different, the wallet is merely the keypair, also an application to manage the account.

#