JavaScript for beginners

Solutions for problems that JavaScript newbies face
25 July 2017   463

Lightweight interpreted or JIT-compiled programming language with first-class functions

JavaScript ("JS" for short) is a full-fledged dynamic programming language that is applied to an HTML document, and can provide dynamic interactivity on websites. It was developed by Brendan Eich, co-founder of the Mozilla project, Mozilla Foundation and Mozilla Corporation.

You can do a lot with JavaScript. You can start with small, simple functions, such as carousels, image galleries, changing layouts and a response to the pressing of buttons. When you become more experienced in the language, you can create games, animated 2D and 3D graphics, full-scale applications with databases and much more!

JavaScript itself is fairly compact, but very flexible, and developers have written many tools on top of the main JavaScript language, which unlock a huge number of additional functions with very little effort.

JS is one of the most popular programming languages in the world. Therefore, this is one the most popular programming language that beginners would like to learn. We’ve made a research and found out, what are the main issues that beginners face when learning JavaScript are:

  • javascript array
  • javascript switch
  • javascript substring
  • javascript map
  • javascript foreach
  • javascript date

Let's go thru this list and find out, what difficulties can newbies face and how to solve them.

JavaScript Array 

Array is a type of object that is intended for storing numbered values and offers additional methods for convenient manipulation of such a collection.

They are usually used to store ordered collections of data, for example - a list of products on the page, students in a group, etc.

If you have a list of items (a list of cities names, for example), storing the city names in a single variables could look like this:

var car1 = "Moscow";
var car2 = "London";
var car3 = "Paris";

However, what if you want to go through the cities and find a specific one? And what if you had not 3 cities, but 300? The solution is an array! An array can hold many values under a single name, and you can access the values by referring to an index number.

You can learn more at:

  • W3Schools
  • Tutorials Point
  • LearnJSRu

JavaScript Switch 

The switch construct replaces several if at once. It is a more visible way to compare the expression with several options at once.

Let's have a look at it:

switch(x) {
  case 'val1':  // if (x === 'val1')

  case 'val2':  // if (x === 'val2')

  • X is checked for strict equality to the first value of val1, then to the second val2 and so on.
  • If the match is set - the switch starts executing from the appropriate case directive and then to the next break (or until the end of the switch).
  • If no cases match, the default option is executed (if any).

You can learn more at:

  • W3Schools
  • LearnJSRu
  • Mozilla

JavaScript Substring

In JavaScript, any text data is a string. There is no separate type of "symbol", which is in other languages.

You can create string in this way:

var text = "my string";

var anotherText = 'my string 2';

var str = "012345";

In JS, there are 3 methods for taking substring, with slight differences between them: substr, substring, slice.

substring (start, end) method returns a substring from the start position to, but not including, end.

var str = "stringify";
alert(str.substring(0,1)); // "s"

If there is no end argument, it goes to the end of the line. 

var str = "stringify";

Learn more about sting and substing in JS here:

  • W3Schools
  • LearnJSRu
  • Mozilla

JavaScript Map

Map allows to store records like key: value.

Unlike objects in which keys can only be strings, the Map key can have an arbitrary value, for example:

'use strict';

let map = new Map();

map.set('1', 'str_1');   
map.set(1, 'num_1');    
map.set(true, 'bool_1');

alert( map.get(1)   ); // 'num_1'
alert( map.get('1') ); // 'str_1'

alert( map.size ); // 3

As you can see from the example above, get and set methods are used to store and read values. Both keys and values are stored "as is", without type conversions.

The map.size property stores the total number of records in map.

Learn more about JS Map here:

  • W3Schools
  • LearnJSRu
  • Mozilla

JavaScript forEach

Method arr.forEach (callback [, thisArg]) is used to enumerate the array. It calls the callback function for each element of the array.

This function passes three parameters callback (item, i, arr):

  • Item is the next element of the array.
  • I is his number.
  • Arr is an array that iterates.

For example:

var arr = ["Apple", "Orange", "Lemon"];

arr.forEach(function(item, i, arr) {
  alert( i + ": " + item + " (array:" + arr + ")" );

The second, optional argument forEach allows you to specify the this context for the callback. TheforEach method returns nothing, it is used only for enumeration, as an "elegant" option than the usual for loop.

  • W3Schools
  • LearnJSRu
  • Mozilla

JavaScript Date

Date objects are used to work with the date and time in JavaScript.

To create a new Date object, use one of the syntaxes:

new date ()
Creates a Date object with the current date and time:

var now = new Date ();
alert (now);

new date (milliseconds)
Creates a Date object whose value is equal to the number of milliseconds (1/1000 seconds) since January 1, 1970 GMT + 0. 

// 48 hours since 01.01.1970 GMT+0
var Jan02_1970 = new Date (3600 * 48 * 1000);
alert (Jan03_1970);

new date (datestring)
If a single argument is a string, use the Date.parse call to read the date from it.

new date (year, month, date, hours, minutes, seconds, ms)
You can create a date using the components in the local time zone. For this format, only the first two arguments are required. Missing parameters, starting with hours are considered equal to zero, and date - to one.


  • The year must be 4 digits.
  • The month count starts from zero 0.

For example:

new date (2012, 0, 1, 0, 0, 0, 0); // // January 1, 2012, 00:00:00
new date (2012, 0, 1); // same, hours / seconds defaults to 0

The date is specified to within milliseconds:

var date = new date (2012, 0, 1, 2, 3, 4, 567);
alert (date); // 1.01.2012, 02: 03: 04.567

  • W3Schools
  • LearnJSRu
  • Mozilla

How to Code Ethereum DApps

The article introduces to you the Ethereum DApps development. We'll discover all tools you need to write your first DApp. From running your own blockchain inside Docker to interacting via js with a deployed smart contract.
01 February 2018   3908

This article covers several subjects:

  • How to start and run private Ethereum node
  • How to write and compile your first smart contract
  • How to interact with smart contracts via Mist browser (ÐApp)

Before we start you got to have:

  • Installed Docker (Download page)
  • Mist wallet to work with ÐApp (Download Mist, we need exactly Mist, not Ethereum-Wallet-*)

All code we'll write you can find at

How to start and run private

Ethereum node

We need a tool to run blockchain. The most popular option is Geth — Official golang implementation of the Ethereum protocol.

To run a Docker container with Geth we need to create the Dockerfile with content:

FROM ethereum/client-go
ADD ./genesis.json /root/

Our folder should contain a genesis.json file

    "config": {
        "chainId": 42,
        "homesteadBlock": 0,
        "eip155Block": 0,
        "eip158Block": 0
    "difficulty": "1",
    "gasLimit": "2500000",
    "alloc": {

Let's inspect a few fields from genesis.json: chainId and difficulty.

chainId we need to identify our private blockchain. We already have some reserved values. For the main net (also called Frontier) we have 1. 2 and 3 also reserved (you can check it at We need to choose a new one to prevent future difficulties such as Geth will try to download blocks from existed blockchains and fails to validate it because other options are different.

difficulty is needed to define a minimum accepted value of difficulty. The difficulty will automatically adjust in order to follow rules: will raise if new blocks are created in less then 9 seconds or decrease if miners struggle to find a solution in less then 20 seconds. If we set 0, the rule will no longer be applied and Geth starts to create tens new blocks per second.

Let's create a new Docker image

$ docker build . -t private-net-docker

And now let's run the command to initialize the blockchain

$ docker run -v $(pwd):/root/ private-net-docker init /root/genesis.json

-v $(pwd):/root/ — will synchronise foler /root/ inside container with our current hosts machine

init /root/genesis.json — the command init we're passing to Geth with an argument

Right now we have an .ethereum/ folder with content:

├── geth
│   ├── chaindata
│   │   ├── 000001.log
│   │   ├── CURRENT
│   │   ├── LOCK
│   │   ├── LOG
│   │   └── MANIFEST-000000
│   └── lightchaindata
│       ├── 000001.log
│       ├── CURRENT
│       ├── LOCK
│       ├── LOG
│       └── MANIFEST-000000
└── keystore

4 directories, 10 files

The geth folder contains blockchain files.

The keystore folder contains private keys encrypted by password. Let's generate a new wallet. More precisely a wallet it is just a private key because an address is a hash function from the public key (which is also a cryptographic function from a private key).

$ docker run -v $(pwd):/root/ -it private-net-docker account new The current command will ask you to type your passphrase and use it as a secret key to encrypt your wallet file.

Let's create a wallet

$ docker run -v (pwd):/root/ -it private-net-docker account new

Your new account is locked with a password. Please give a password. Do not forget this password.
Repeat passphrase:
Address: {9bd431ec62f0d581872bc610f2b74f0b6eeb1d06}

If we take a look at our wallet file, we'll see (passphrase is "test"):

$ cat .ethereum/keystore/UTC--2018-01-24T17-32-52.514528177Z--9bd431ec62f0d581872bc610f2b74f0b6eeb1d06

    "address": "9bd431ec62f0d581872bc610f2b74f0b6eeb1d06",
    "crypto": {
        "cipher": "aes-128-ctr",
        "ciphertext": "f3ee7771de9862ce4e1ad1fdc46921d63294196f49192b4f174e629c7efeaa06",
        "cipherparams": {
            "iv": "e00fe4ef5de621b1292f5130b6ef461e"
        "kdf": "scrypt",
        "kdfparams": {
            "dklen": 32,
            "n": 262144,
            "p": 1,
            "r": 8,
            "salt": "b3da6b0fc66c9d8254c7314ee844e2773b090c8e73b7efc845521d9b06a86d36"
        "mac": "7f8825010ed6b0644127115ebdac7d80ff37fbdf34034dd5828fef124ed02e8b"
    "id": "4c6b6254-b0fb-4f5c-86d6-ee1a7be68d05",
    "version": 3

On the current stage we have an initialised private blockchain and we've generated a wallet. It's time to run our blockchain' node to mine the first block. To mine any block we don't need transactions. We'll mine and still get the reward for the new block (except, of course, fees for handling transactions).

$ docker run -p 8545:8545 -p 8546:8546 -v $(pwd):/root/ private-net-docker --etherbase=0x<YOUR_ADDRESS> --networkid 42 --mine --minerthreads=1 --rpc --rpcaddr --rpcapi "db,eth,net,web3,personal"

<YOUR_ADDRESS> should be replaced with generated address, in our case it will be etherbase=0x9bd431ec62f0d581872bc610f2b74f0b6eeb1d06

We are starting to see the messages

NFO [01-24|15:17:29] Starting mining operation

INFO [01-24|15:17:29] Commit new mining work number=1 txs=0 uncles=0 elapsed=208.389µs
INFO [01-24|15:17:33] Generating DAG in progress epoch=0 percentage=0 elapsed=2.717s
INFO [01-24|15:17:36] Generating DAG in progress epoch=0 percentage=1 elapsed=5.437s
INFO [01-24|15:17:39] Generating DAG in progress epoch=0 percentage=2 elapsed=8.048s
INFO [01-24|15:17:41] Generating DAG in progress epoch=0 percentage=3 elapsed=10.703s

The first block has been mined. Also, we're starting to see the messages about DAG generating (Directed Acyclic Graph). That graph required for "Proof of Work" conception. It needs to be generated every 30,000 blocks. The generation takes much power to compute. The data will be placed inside .ethash folder and takes around 1GB. The size will grow every 30,000 blocks.

Right now DAG files of the current Ethereum network are taking 2.29GB. After DAG has been generated, the geth node will start mine new blocks and also pre-generate next DAG for the 30,0001 block.

Our first smart contract

The general concept of smart contract is pretty simple if you're familiar with OOP (object-oriented programming). You can think of it like it is just a regular a class object and class object has a state (variables) and also has functions to work with this variables or call other classes.

You can call smart contract function by sending a transaction to its address with a special `data` argument. The data argument is formatted in a special way to produce an execution of smart contact's method with some arguments. It isn't required to transfer Ether, you can make an empty transfer transaction but just ensure to pay a fee to miners to handle the transaction. If a method of smart contract you want to execute is not modifying any variables, just return some value, you can call it via Geth's API without any fees. The language you choose to write smart contact should be compiled to bytecode that Ethereum VM (Virtual Machine) can run. The most popular language for that goal now is Solidity.

Our first smart contract


pragma solidity ^0.4.16;

contract Test {
    uint public id = 0;

    function getId() public view returns (uint id_counter) {
        return id;

    function nextId() public {

What is going on here?

pragma solidity ^0.4.16; — we're defining compiler version

contract Test { — we're naming our "class"

uint public id = 0; — we're defining a class variable. Then we need to create some functions to access and change our variable.

function getId() public view returns (uint id_counter) { return id; }

public — scope (also can be internal)

view — function's type, view function are prohibiting to modify a state of the contract (type also can be pure, view, payable)

returns (uint id_counter) — declaration of function's return

function nextId() public { id++; } — that function are just adding 1 to the id variable.

Let's save smart contract to the test.sol file


We're ready to compile our first smart contract. In order to do that, we need to install solidity compilator. Dockerfile

FROM ethereum/solc:stable

WORKDIR /srv/app/

ADD ./ /srv/app/

$ docker build . -t contract


$ docker run -v $(pwd):/srv/app/ contract --optimize --abi --bin /srv/app/test.sol

Compile command's output

======= /srv/app/test.sol:Test =======


Contract JSON ABI

We can see two blocks

Binary — smart contract's binary code

Contract JSON ABI — JSON interface to interact with a smart contract


One way to deploy smart contract is using Mist wallet. By default, Mist is running its own version of Geth. In order to connect Mist to our node, we need to pass a few arguments. When we started the geth one of the arguments was --rpcapi "db,eth,net,web3,personal" — here we have defined modules we want to allow using with rpcapi. We need to be careful and disallow any external connections to our network with running geth.

Run Mist (Mac OS)

/Applications/ --rpc http://localhost:8545 --swarmurl "null" Mist, страница кошелька The initial page it's a great example of decentralized application (DApp). Mist is just a browser with the special interface for a decentralized application. As an example, the wallet part is a DApp itself which is located at To publish our first smart contract we should go to the contracts page (top right corner), then we need to click to the "DEPLOY NEW CONTRACT" link (keep on mind that it is just a DApp's interface). Then, on the deploy page, we need to change tab to the binary code publication, paste our binary code and click on the Deploy button. Mist, публикация спартконтракта After we will finish publishing contract we need to get its address. We have two ways to do it: in console, we can see the info about contract creation and its address

INFO [01-24|17:36:17] Submitted contract creation fullhash=0x5999b523138e2c6dd93b770f7d7d53a21e19a25848c3b1c2cc9b1a9255adc687 contract=0x82087D6c27994B4a88975610f19b6bE7A5125E9C

Also, we can go the main page of the wallet and check the transactions block on the bottom. Mist, публикация смартконтракта Right now we are running our Ethereum private node, we have done our first smart contract and have published it to our blockchain. It's time to create a decentralized application.

Decentralised application

What is a DApp? It's a frontend application that can send a request to the Geth API. If you open a DApp via Mist browser, Miss will provide a handy interface to interact with Geth. Then, Geth will interact with the blockchain to make a transaction or read the swarm's database.

Let's take a look at some examples how we can interact with Mist (or with Geth directly if we want to) by our code of frontend application. To do this we need to install web3 js library via npm. Then we'll use web3 to connect to the Geth. To perform transactions we also need to define our Ethereum address.

var Web3 = require('web3');

window.client = new Web3(web3.currentProvider);
window.coinbase = '0x9bd431ec62f0d581872bc610f2b74f0b6eeb1d06'

Next, we'll define function to call getID() smart contract's method .

var initContract = function () {
    var abi = [{ "constant": true, "inputs": [], "name": "getId", "outputs": [{ "name": "id_counter", "type": "uint256" }], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": false, "inputs": [], "name": "nextId", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": true, "inputs": [], "name": "id", "outputs": [{ "name": "", "type": "uint256" }], "payable": false, "stateMutability": "view", "type": "function" }]
    var data = '606060405260008055341561001357600080fd5b60de806100216000396000f30060606040526004361060525763ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416635d1ca6318114605757806361b8ce8c146079578063af640d0f14608b575b600080fd5b3415606157600080fd5b6067609b565b60405190815260200160405180910390f35b3415608357600080fd5b608960a1565b005b3415609557600080fd5b606760ac565b60005490565b600080546001019055565b600054815600a165627a7a72305820414c782c7578801973a19b44d5cd532afbdd32a894e2d2dc955a3da88db33b230029'

    return new window.client.eth.Contract(abi, '0x82087D6c27994B4a88975610f19b6bE7A5125E9C');

window.getId = function () {
    var contract = initContract();

    contract.methods.getId().call().then(function (data) {
        document.getElementById('res').innerHTML = data;

We have defined two functions: window.getId() and initContract().

The initContract() function is defining data of our smart contract: JSON interface, code and address. It is required by the web3 lib to arrange requests to the geth's API.

The window.getId() function calls the getId() of smart contract and then will write the result to the console.

Ok, we have a general understanding what is going on here. Let's do some practice.

  1. First, clone the github repository
  2. Go to the dapp folder
  3. Run the $ docker build . -t dapp command
  4. Edit the file /src/app.js to write your address on the line 4 to coinbase and smart contract's address on the line 20 into the ' ' string
  5. Run the application
$ docker run -p 8080:8080 -v $(pwd):/srv/app/ dapp npm i
$ docker run -p 8080:8080 -v $(pwd):/srv/app/ dapp npm run start

Here is the final stage. Let's test that everything is working nicely. Open the page http://localhost:8080 in Mist browser and developer tools for that page.

Mist, инструменты разработчика

In console we can call the methods of our ÐApp: getId() и nextId().

Взаимодействие с DApp в Mist

Keep in mind that getId() will return 1 only after the transaction have been mined.

That's all.

We have successfully created a private Ethereum network, completed and compiled our first smart contract and wrote the decentralized application for it.

A few words about ICO. Tokens are the same smart contracts, i.e. classes with variables that are keeping track of the state. In order to create a smart contract which can call itself token, the smart contract should have methods with predefined names. You can find that names of methods in ERC20 standard. As an example, if you call a special function of smart contract and send some Ether, the function will increase a value of smart contract's variable.

Boris Kuznetsov, Senior Software Engineer at Evrone