0

Introduction to Javascript and Solidity- Part 1: Javascript

Ethereum has gained a unique niche for itself in the cryptospace as a smart contract platform. Developers from all around the world can enter create their own decentralized applications right on top of the Ethereum blockchain. However, in order to do that, developers must be very well-versed in solidity, the language that is used to code smart contracts.

Introduction to Javascript and Solidity (Blockgeeks)

Introduction to Javascript and Solidity

The purpose of this guide is to clear up your basics in solidity. If you want a more advanced course then we suggest that you go through our solidity courses. This guide is only going to clear up your basics.

So, before you begin solidity there are two things you should know:

If you want to learn the basics of the blockchain technology and Ethereum in general then you can look up our guides to clear this up for you.

So, now we come to the second point.

Why do you need the basic knowledge of JavaScript?

Firstly, as the solidity document states, it is influenced by JavaScript. Secondly, as many people have noted, solidity is pretty similar to JavaScript when it comes to syntax. The reason for this is pretty simple.

JavaScript happens to be one of the most in-demand and popular languages in the world. The Ethereum founders felt that if they modeled solidity after JavaScript, developers will be able to pick it up faster. So, let’s start off with JavaScript before we delve into solidity, which we will cover in part 2 of this article.

Javascript and Solidity Introduction

JavaScript was created by Brendan Eich, who will later go on to find Mozilla Firefox and Brave browser. JavaScript or JS is a lightweight, dynamic, and object-oriented programming language. JavaScript, along with HTML and CSS forms the 3 pillars of web designing. HTML helps put content on your website while CSS helps you with the design layout.

So, what exactly does JS do?

Before JavaScript came along, websites used to be extremely static. JavaScript brought along the era of more user-friendly and dynamic websites. When you keep this in context and realize how much business is done online, you can see why you can make such a strong case for Javascript. JS single-handedly made websites more user-friendly.

Even though originally JavaScript was supposed to be a client-side script, several implementations such as node.js have allowed for server-side implementation as well. JavaScript is officially managed by Mozilla Foundation, and new language features are added periodically.

Features of JavaScript

The following are the features of JavaScript

  • All modern browsers have a built-in JavaScript engine. In fact, we will take a closer look at this later
  • JavaScript has a structured programming syntax and has functional and block scoping. Don’t worry we will cover scoping in a bit
  • JavaScript is dynamically typed. Meaning, a variable which was storing integer values a moment ago can store a string during runtime
  • JavaScript is an object-oriented programming language. We will cover this in a bit
  • JavaScript is a functional language. So it supports modulation via functions
  • JavaScript also supports implicit and explicit delegation.
  • JavaScript is case sensitive, so “width” is different from “Width”.

Alright, so let’s just look into each of these features in details.

Feature #1: Browsers with Built-in JS

We are going to be using Google chrome for this.

Just open a new tab on your browser. Right-click anywhere on the browser and click on “Inspect.”

Introduction to Javascript and Solidity (Blockgeeks)

The moment you click on it, you are going to see this window:

Introduction to Javascript and Solidity (Blockgeeks)

This is the in-built console in the google chrome browsers. In order to fiddle around with the JS tools, you can simply go on the Console part. Which is here:

Introduction to Javascript and Solidity (Blockgeeks)
Alright… so let’s get coding!!!

You can do simple mathematical operations here:

Introduction to Javascript and Solidity (Blockgeeks)

Or, if you want, you can do the simple “Hello World” program right here.

For this, we are going to type “console.log(‘Hello World’);”

Introduction to Javascript and Solidity (Blockgeeks)

“console.log()” is the function which allows us to print outputs on the console. Also, notice how we ended the function with “;”. In JS, you need to use the semi-colon to end instructions.

The moment you enter the command and press “Enter” you are going to get that output in the console itself.

Interestingly enough, if you want the output to pop up on your screen then you can simply use the “alert()” function. So if you type “alert(‘Hello World’);” on your console then you will see this.

Introduction to Javascript and Solidity (Blockgeeks)

Pretty cool right?

Now, we just wanted to get you started on the most basic form of programming to show you the JS engine inside the browsers. We will go deeper into programming in a little later.

Feature #2: Functional and Block Scoping

In order to understand the difference between functional and block scoping, you must know a little bit about variable declaration in JS.

In C++, when you want to declare an integer variable you can do this:

 

int a;

 

In Java, you don’t have to worry about the individual data type, since the language is dynamically typed. You have three options that you can use to declare your variable: var, let, and const.

Var

Var is a very straightforward way of assigning and variables.

var a = 10;



console.log(a);



// it returns



10



a = 20;



//to show dynamic reassignment



console.log(a);



20

So, var seems pretty straightforward, right?

However, it is not considered a good practice to use var in programming anymore because var variables are “function scope”. This means that the var variables are declared inside a function then they are only available inside the function, or if not created inside a function, they are “globally scoped”, meaning they are available everywhere.

Let’s see how this works. Consider the following program (Taken from this article) :

 

function setWidth(){

   var width = 100;

   console.log(width);

}



width;

If you try executing this program, then you will see the following error.

Introduction to Javascript and Solidity (Blockgeeks)

Can you guess why?

The “width” which we have declared as “var” was declared inside the function. This is why, it is valid only inside the scope of the function and nowhere else.

Similarly, now we have the other extreme.

Consider the following code:

 

var age = 100;

 if (age > 12){

   var dogYears = age * 7;

   console.log(`You are ${dogYears} dog years old!`);

 }

Two things that you need to note about the code above.

Firstly, the use of “$(dogYears)”, this ensures that you are printing the value of the variable. Secondly, the var variables are not declared inside a function. Because of this, they are not bound by a scope and hence can be called even post-execution.

You are 700 dog years old!

However, now if you go on the console and call dogYears it will return 700 to you.

Do you know why this happened?

By not declaring the variable inside a function, we made it global.

So keep this in mind for future reference, var is not limited to the curly brackets. It is the function which defines the scope.

This is why, instead of var, we use let and const.

Why Use let and const?

In stark contrast, let and const is scoper to a block that function. A block is defined as a set of opening “{“ and closing “}” curly brackets.

So, if we had declared dogYears with “let” as opposed to “var” what do you think will happen?

 

var age = 100;

 if (age > 12){

   let dogYears = age * 7;

   console.log(`You are ${dogYears} dog years old!`);

 }

It is declared inside an “if” block, so the lifetime of that variable is over as soon as the block ends.

Note: We will cover the if-else function in a bit.

So, now when you execute this program (inside visual code) and call dogYears in the console you will get the following message:

“Uncaught ReferenceError: dogYears is not defined.”

You can also use const instead of let to declare these variables. However, using const makes your variables immutable. So, if you plan to change the value during runtime, then you will get an error:

Introduction to Javascript and Solidity (Blockgeeks)

Feature #3: Dynamically Typed

Dynamically typed means that the variables can change their types throughout the execution of the program. So, if you a variable which is storing a string, during execution it can store an integer as well.

So, go on your console and execute this:

let var2 = 10;

var2 = ‘Hello’;

If you call var2 now, it will return “Hello’, even though you initially declared it with an integer.

In fact, why not do something more in-depth and actually observe how the variable is changing its state?

For this, we use the “typeof()” function. This function specifically tells you what is the type of the variable that you are using. Now consider the same example that we gave above.

Introduction to Javascript and Solidity (Blockgeeks)

So, when var2 had a number in it, its type was number. However, the moment it stored “Hello” it changed to string.

Feature #5: Object-Oriented Programming Language

JavaScript is an object-oriented programming (OOPs) language as opposed to a process-oriented one. Process-oriented languages like C utilized programs where a list of instructions that acted on memory.

OOPs, on the other hand, allows for the creation of a blueprint called “class” from where one can generate objects which can interact with each other. These objects execute the program.

Now, there are four pillars to OOPs:

  • Encapsulation
  • Abstraction
  • Polymorphism
  • Inheritence

Introduction to Javascript and Solidity (Blockgeeks)

Encapsulation

Encapsulation is the idea of wrapping together data and function within one unit. The idea is to hide the initial state of the objects and to bind everything in a solid pack.

Abstraction

Abstraction means that a user can use the program without getting into the complications behind it.

Think of a car.

When you drive a car, all that you care about is putting your key in and maneuvering the vehicle in a way that you don’t hit anything else. You don’t care about how the engines work and how the ignition is burning your fuel.

Inheritance

Inheritance is one of the most important properties of OOPs.

Inheritance allows an object or a class to based upon another object or a class and retain some of its implementations. In most class-based object-oriented languages, an object created through inheritance acquires most of the properties and behaviors of the parent object

Polymorphism

Polymorphism is the property by which an operator in the language can have more than one properties. The most famous example of this is “+”. Not only is it used as the mathematical addition operator, but it can also be used to combine two strings into one as well. This is called concatenation.

Introduction to Javascript and Solidity (Blockgeeks)

Feature #6: Implicit and Explicit Delegation

Delegation basically means that an object can be defined in the terms of another object. Delegation pretty much means the delegation of responsibility. Now delegation can be both explicit or implicit.

With explicit delegation, an object can explicitly delegate a message to any other object it has knowledge of. With implicit delegation, an object can explicitly designate another object as its “parent”. Messages that are not understood by the receiving object are automatically (implicitly) delegated to this parent.

Implicit delegation can be further broken down into two more categories:

  • Unanticipated delegation, where the delegation structure can be changed dynamically during runtime.
  • Anticipated delegation, where the objects cannot change the parent object that they have inherited from during their life-time.

Before We Start Coding

Now that we are done with the theory, for the most part, let’s start coding! In order to execute these programs, you will need an environment where you can execute them.

We will be using the Visual Studio Code. In order to do that, go to code.visualstudio.com and download the latest version of Visual Studio.

Once you are done installing that, you will see this screen.

Introduction to Javascript and Solidity (Blockgeeks)

Now, go on File ->Open

After that, you need to create a folder. Let’s call this folder “Blockgeeks-JS”.

Introduction to Javascript and Solidity (Blockgeeks)

After that, there are two things that you need to do:

Introduction to Javascript and Solidity (Blockgeeks)

And after clicking on that button, create a file called “index.html”.

Introduction to Javascript and Solidity (Blockgeeks)

On the first line of code in this new file, type “!” followed by a tab.

Introduction to Javascript and Solidity (Blockgeeks)

The moment you do that, you will see a block of HTML code appearing on the screen. You don’t really need to care about this code. It is basically providing a host where we can use our JS code.

After that, click on the extensions button as indicated below:

Introduction to Javascript and Solidity (Blockgeeks)

Now search for “Live Server” and install the extension.

Introduction to Javascript and Solidity (Blockgeeks)

When that is installed, go to your “index.html” file and select “Open With Live Server”.

Introduction to Javascript and Solidity (Blockgeeks)

What this now does, is that it allows you to execute the JS programs in your default browser. In fact, the moment you choose this option, a new tab should open up on your browser.

Alright so, now let’s look at our HTML code in “index.html”.

 

<!DOCTYPE html>

<html lang="en">

<head>

   <meta charset="UTF-8">

   <meta name="viewport" content="width=device-width, initial-scale=1.0">

   <meta http-equiv="X-UA-Compatible" content="ie=edge">

   <title>Document</title>

</head>

<body>

   

</body>

</html>

Now you can start coding in the body area. Eg. let’s add a header tag in the body area and fill it with some content.

 

<!DOCTYPE html>

<html lang="en">

<head>

   <meta charset="UTF-8">

   <meta name="viewport" content="width=device-width, initial-scale=1.0">

   <meta http-equiv="X-UA-Compatible" content="ie=edge">

   <title>Document</title>

</head>

<body>

<h1> WELCOME TO BLOCKGEEKS!</h1>    

</body>

</html>

Now, save this file and look at the new tab which opened up.

Pretty cool right!

So, now let’s start with some JavaScript.

In the body, right below the header tag, let’s add the script tag and print “Hello World” on the console.

 

<!DOCTYPE html>

<html lang="en">

<head>

   <meta charset="UTF-8">

   <meta name="viewport" content="width=device-width, initial-scale=1.0">

   <meta http-equiv="X-UA-Compatible" content="ie=edge">

   <title>Document</title>

</head>

<body>

<h1> WELCOME TO BLOCKGEEKS!</h1>    

<script> console.log(Hello World);</script>

</body>

</html>

After that, just go the tab. Right Click on it and choose “inspect” and then go to the console tab like we have shown you before.

This is what you will see:

NOTE: The reason why we put the script part in the Body section instead of the Head section is that we don’t want the JavaScript to run even before the site content loads up.

Now, standard programming best practices state that you shouldn’t be coding JS stuff into the HTML program. The HTML part and the JS part should be kept separate.

Also, scripts can get really long and complicated so it doesn’t make sense to try to squeeze all the code inside the HTML code.

So, this is why we will create another new file and name it “index.js”.

Introduction to Javascript and Solidity (Blockgeeks)

In this part, we are going to put everything that we have put inside the script tag, namely:

However, the “index.html” file is the main file. We should put in another line of code which helps the main file to refer to the JS file. The way we are going to do that is by making a slight modification.

<!DOCTYPE html>

<html lang="en">

<head>

   <meta charset="UTF-8">

   <meta name="viewport" content="width=device-width, initial-scale=1.0">

   <meta http-equiv="X-UA-Compatible" content="ie=edge">

   <title>Document</title>

</head>

<body>

<h1> WELCOME TO BLOCKGEEKS!</h1>    

<script src=index.js></script>

</body>

</html>


What this does is that it shows the HTML program where exactly the JS program is located. Also, please make sure to ALWAYS SAVE your .html and .js files.

What this does is that it shows the HTML program where exactly the JS program is located.

Also, please make sure to ALWAYS SAVE your .html and .js files.

Alright, so that pretty much covers the basics. Let’s do some coding!

Simple Coding

#1 Mathematical Operations

Let’s do some basic mathematical operations on JS.

let a = 10;

let b = 20;

let c = 30;

let d = a+b*c;

console.log(d);

What do you think the answer will be?

Do you think that the answer is 900?

Well, let’s execute the program and see what we get?

Introduction to Javascript and Solidity (Blockgeeks)

610.

Why do you think we got that?

You see, instead of going from left to right, JS follows the PEMDAS where:

P = Parenthesis

E = Exponent

M = Multiplication

D = Division

A = Addition

S = Subtraction

So, the operation follows this order of priority in an ascending order:

P

E

MD

AS

Multiplication and Division have the same preference order. So does Addition and Subtraction.

#2 Arrays

An array is a data structure that contains a group of elements. Typically these elements are all of the same data type (not necessary in the case of JavaScript), such as an integer or string. Arrays are commonly used in programs to organize data so that a related set of values can be easily sorted or searched.

Check out the code below:

 

let names = ['Mark', 'Will'];

console.log(names);

Introduction to Javascript and Solidity (Blockgeeks)

See that arrow next to “(2)”? When you click on it, it expands to reveal the following:

According to this:

  • The length of the array is 2 because it has two elements
  • The index of the first element “Mark” is 0
  • The index of the second element “Will” is 1

We can dynamically add elements to the array during runtime as well. Here check it out:

 

let names = ['Mark', 'Will'];

names[2] = 'Kumar';

console.log(names);

When you print this in the console, you will get:

As you can see, we got the array to expand by a single element during runtime. Now, in Javascript, you don’t need to add the same data type. How about we add a number to the array?

let names = ['Mark', 'Will'];

names[2] = 'Kumar';

names[3] = 1;

console.log(names);

The output now looks like this:

Introduction to Javascript and Solidity (Blockgeeks)

Before we finish up arrays. There is one more thing.

You can check the length of the array like this:

let names = ['Mark', 'Will'];

names[2] = 'Kumar';

names[3] = 1;

console.log(names.length);

Now the output looks like this:

Introduction to Javascript and Solidity (Blockgeeks)

The length of the array is 4.

#3 Functions

Up next we have functions which are easily one of the most important parts of the programs. By declaring functions you are going to make your work much more straightforward and reduce a lot of repetition. The functions contain a unit of code that works on various inputs, many of which are variables, and produces concrete results involving changes to variable values or actual operations based on the inputs. One can call these functions during the program runtime and execute the code.

Let’s see an example.

function urgent(){

console.log('Watch JRE 1169');

}

urgent();

The function above prints a message. After we have declared the function, we simply call the function to execute it. Let’s look at the output:

Introduction to Javascript and Solidity (Blockgeeks)

Now, let’s add some more spice to the mix.

function urgent(num){
console.log('Watch JRE ' + num);
}
urgent(1169);

Let’s look at the output:

Introduction to Javascript and Solidity (Blockgeeks)

Now, let’s increase the number of parameters in the function and the number of function calls.

function username(firstName, lastName){

   console.log('The name is ' + firstName + ' ' + lastName);

}

username('Vitalik', 'Buterin');

username('Satoshi', 'Nakamoto');

So, when you execute this code you will get the following output:

Introduction to Javascript and Solidity (Blockgeeks)

One of the best properties of the function is to return values. So you can have a function which does complex mathematical processes and use it to return values to a variable.

How about we declare a function which calculates the square of a number and returns the value:

function square(num){

   return num * num;

}

let result = square(2);

console.log('The square of 2 is ' + result);

The output will be:

Introduction to Javascript and Solidity (Blockgeeks)

#4 Conditional Statements

Conditional statements like “if-else” are a cornerstone of programming. You can do the same in JavaScript as we have already seen before. Consider this code:

 

let a = 20;

let b = 30;

if (a > b){

   console.log(a + ' is greater');

} else {

   console.log(b + ' is greater');

}

This is a simple program which checks and prints the greater number.

The above code gives the following output:

Introduction to Javascript and Solidity (Blockgeeks)

#5 Loops

Looping allows the program to execute the code given inside the loop to be executed a specified number of times.

Before we continue you must know what incrementation (or decrementation means).

Incrementation means increasing the value of a particular variable by a given amount. So, if we want to increase the value stored in a particular variable, like “a”, by 1 we do:

a = a +1;

OR to make it more efficient, we simply do “a++”, which is the same as a = a + 1;

Similarly, to decrement value we do:

a = a-1;

Or

a–;

Ok, so back to loops.

The loop statements that are used in JavaScript are:

  • While
  • Do-While
  • For

While Loop

The while loop is the simplest form of a loop statement. It works like this:

while(condition) {

 

Statement;

 

Increment;

}

Consider this:

 

let i = 1;

while(i < 3){

console.log(i);

i++;

}

Executing this code gives the following output:

So, what happened here?

We initialized a variable to 1, and instructed the program to print the variable as long as the value of it is less than 1. Also, inside the loop we kept on incrementing the value of “i”. If we hadn’t incremented it, the program would have been in an infinite loop.

Do-While Loop

The Do-While loop looks like this:

do{

Statement;

Increment;

} while(condition);

So, as opposed to the while loop, the do-while loops runs the code first and checks the condition later.

Now, see this code:

 

let i = 1;

do{

   console.log(i);

   i++;

} while(i<3);

 

This will print:

So, what is the difference between the while and do-while during program execution. Well, check the following example:

let i = 1;

console.log('First we will check the while loop');

while (i < 1){

   console.log('This is inside the while loop');

}

console.log('Now we are going to check do-while');

do{

   console.log('This is inside the do-while loop');

} while(i < 1);

console.log('We are outside the loops now');

 

 

The output is:

Introduction to Javascript and Solidity (Blockgeeks)

So, what are we doing here?

First, we executed the while loop. Since this loop checks the condition beforehand, it didn’t even allow the compiler to go inside its body. Hence the statement inside the while loop wasn’t executed.

However, since the do-while loop executes the statement before checking the condition, the statement inside the body was executed.

For Loop

The for loop has the following structure:

for( Initialization; Condition; Incrementation)

{

 

Statement;

 

}

So, the for loop takes care of the condition and the incrementation in its parameters itself. How does this look in runtime?

 

for (let i = 1; i <= 5; i++)

{

   console.log(i);

}

This program gives the following output:

Introduction to Javascript and Solidity (Blockgeeks)

Object-Oriented Programming In JavaScript

Alright, so now we come to one of the most important aspects of JavaScript, object-oriented programming. Consider the following piece of code:

 

let Max = {

   school: 'Central High',

   age: 14,

   birthplace: 'New York'

};

console.log(Max);

So, we have declared an object named “Max” and declare the elements of this object, name:

  • Where Max goes for school
  • What is Max’s age
  • Where was he born

So, when you print the object Max, this is what you get:

Ok, now suppose that Max just had his birthday. How do we change his age?

let Max = {

   school: 'Central High',

   age: 14,

   birthplace: 'New York'

};



Max.age = 15;

console.log(Max);

;

 

So, this is the output we got now:

Introduction to Javascript and Solidity (Blockgeeks)

Now, we are going to declare an object with a function inside it:

 

let circle = {



   area: function() {

       let radius = 2;

       let a = 3.14 * radius * radius;

       console.log('The area is ' + a);

   }

};



circle.area();

 

 

Once again, a pretty straightforward object. We have declared an object called circle which has an area function inside it which computes and prints the area.

Factory Functions

The way we have declared our object above is extremely inefficient when we have to deal with multiple objects. Remember the code we just used. What if we had to calculate the area of two circles? In that case, we have no option but to just repeat the code with different values.

let circle = {



   area: function() {

       let radius = 1;

       let a = 3.14 * radius * radius;

       console.log('The area is ' + a);

   }

};



circle.area();



let circle1 = {



   area: function() {

       let radius = 2;

       let a = 3.14 * radius * radius;

       console.log('The area is ' + a);

   }

};



circle1.area();

 

Now what, if instead of just one function we are dealing with 10 functions per object. Can you imagine how cluttered that code will become?

Also, imagine how difficult debugging the code (scanning the code for potential errors) is going to get if we follow this format.

This is why we use something called “factory functions” to make our code more usable and clean.

Consider the following code:

//create the factory function which takes in one parameter

function createCircle(radius) {

//the function returns this value which is an object

return {

area: function() {

   let area = 3.14 * radius * radius;

   console.log(area);

}

};

}

//creating the object which gets its value from the factory function

let circle = createCircle(1);

circle.area();

//dynamically updating the object by using the same factory function

circle = createCircle(2);

circle.area();

Ok, so let’s see what is going on here.

We have a Factory function called “createCircle()” which sets the blueprint for all the objects that we are going to be creating.

It takes in a parameter called “radius” which helps us in creating different objects with unique values. The function returns the values to a new object. So, when we execute the above code we get the following output:

Introduction to Javascript and Solidity (Blockgeeks)

A factory function is not the only way to initialize an object, you also have constructors.

Constructors

So, how does a constructor look like?

function Circle(radius) {

   this.area = function(){

   let a = 3.14 * radius * radius;

   console.log(a);

}

}

let circle = new Circle(1);

circle.area();

let circle1 = new Circle(2);

circle1.area();

 

Circle() is the constructor that we have used here. According to naming conventions, a constructor must always begin with an uppercase letter. There are two more things you may have noticed in the code that we haven’t talked of before:

  • The “new” keyword
  • The “this” keyword

The “new” keyword helps in the object creation via the constructor. It basically creates a blank, empty object.

The “this” keyword helps in specifying that the variable or the function belongs to this particular object. Eg. in the code given above, “this.area” shows the compiler that either the area function either belongs to the circle object or the circle1 object. The value of “this” inside a function, effectively depends on the object which called it.

Let’s see what happens if we remove the “the” keyword in the code above. Let’s see the output. So, our modified code is:

 

function Circle(radius) {

   area = function(){

   let a = 3.14 * radius * radius;

   console.log(a);

}

}

let circle = new Circle(1);

circle.area();

let circle1 = new Circle(2);

circle1.area()

When you execute this program you will get this error:

Introduction to Javascript and Solidity (Blockgeeks)

Javascript and Solidity: Conclusion

What we have given you here is an extremely basic introduction. JavaScript is a wide subject with a lot of potentials. If you want to stay up-to-date then constant education is needed. We have used the following videos for reference:

https://www.youtube.com/watch?v=PwsigsH4oXw

https://www.youtube.com/watch?v=PFmuCDHHpwk

If you want to educate yourself further then please go and check out their respective channels.

Also, this is it for part 1.

In the next part, we are going to start solidity!!

Like what you read? Give us one like or share it to your friends

0

Related Guides

Join Blockgeeks

Create an account to access our exclusive point system, get instant notifications for new courses, workshops, free webinars and start interacting with our enthusiastic blockchain community. Don’t miss out and join right now!

Already have an account? Sign In

Comments

There are no comments yet