Basics of JavaScript

Mayank Sinha
13 min readFeb 15, 2019

Today, JavaScript has a unique position as the most widely-adopted browser language with full integration with HTML/CSS. JavaScript is incredibly versatile. A person starting to learn development always lists JavaScript as their initial step to start with. So let us learn the basics of JavaScript.

Coding in JavaScript is like telling your computer to follow the instructions' step by step. We can call each instruction as statements. Each statement will end up with a semicolon.

Printing out the stuff on a webpage: Printing out something on the webpage is implemented by:

document.write(“this is to be printed”);

Adding comments: comment is something which is ignored by the browser. It is useful to refer something so that next time while working on that page it would become easier to follow on. it is implemented in two ways:

for a single line comment: //this is the comment

for a long comment: /* this is the comment*/

Variables: variables are basically placeholders for data. A name has to be given while declaring the variable. Declaration of the variable is implemented by:

var nameOftheVariable=25;

The name of the variable can have letters, numbers or underscore symbol. But it can't start with a number. It is case-sensitive.

You can set numbers to variables, you can set numbers with decimal or negation sign to the variables.

ex: var nameOftheVariable= -25.25545;

You can set the string of letters to the variables, but it is done by surrounding the string with a double quotation mark.

ex: var nameOftheVariable= “string of letters”;

While using the double quotation mark, an ambiguity arises. What if the string is already having a double quotation mark? To resolve this issue an escape character is used. It is implemented by a backward slash. An escape character escapes out what is next to it.

ex: var nameOftheVariable= “string of \“ letters\” ”;

Setting a Boolean to a variable is implemented by:

ex: var nameOftheVariable= true;

var nameOftheVariable= false;

Setting a variable to null: Setting a variable to null is like setting an empty variable. It is different from assigning it to zero. It is implemented by:

ex: var nameOftheVariable= null;

Different variables in use:

<!DOCTYPE html PUBLIC “-//WC3//DTD XHTML 1.0 Transitional//EN”
http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html>
<head>
<title>beginner javascript</title>
</head>
<body>
<script type=”text/javascript”>
//this is the comment
/*this is the another way to comment*/
document.write(“this is to print out something on the screen”);
var nameOftheVariable=25;
document.write(nameOftheVariable);
var nameOftheVariable= -25.25545;
document.write(nameOftheVariable);

var nameOftheVariable= “string of letters”;
document.write(nameOftheVariable);

var nameOftheVariable= “string of \” letters\” “;
document.write(nameOftheVariable);

var nameOftheVariable= true;
document.write(nameOftheVariable);

var nameOftheVariable= null;
document.write(nameOftheVariable);

</script>
</body>

</html>

Using variables with strings: By using the plus sign strings are used with variables. Let me show you by example:

coding
the webpage in the browser

Global variables and local variables: Variable which is defined inside the function or whose scope is limited is called a local variable while the variable whose scope is the whole program is called a global variable. A local variable cannot be accessed out of its scope.

Functions: functions are a well-defined set of statements that can be used anytime throughout the JavaScript program. A particular function is assigned a specific job. For that, it can be called any number of times.

Function declaration: function declaration is done by using the keyword ‘function’ followed by parenthesis, which is further followed by curly braces. The parenthesis keeps the parameters inside it, and the function is going to take those parameters for operations. The curly braces involve the set of statements that have to be executed when the function is called.

Function declaration

Alert keyword used to make a pop up on the screen. So when the function will be called, it will show a pop up on the screen.

Function call: A function call is simply done by putting the name of the function followed by its parameters.

Ex: sayOutch():

Return statements: A function can have return statements. It can return any kind of data.

return statements in a function

A function can be called inside another function. So basically when the outer function will be called it will automatically call the inner function.

function calling inside the other function

Built in function: there are some functions in JavaScript, which are predefined. You can directly use them whenever you need them. “Alert” is one of built in function.

Prompt function: prompt is a built in function which basically allows user to enter the data, further the data is stored in a variable. Prompt function takes two parameters. Prompt function evokes pop up window. The first parameter is a string which appears as a dialogue, guiding user, what to enter in text box. The second parameter is also a string which by default resides in text box.

var name= prompt(“first parameter”,“second parameter”);

Set interval function: set interval function takes two parameters. First parameter it takes is a function. The second parameter it takes is a number subjected to tell the browser, in how many milliseconds the function will be called again and again.

Can you guess the output??

Yes, “done” will be printed again and again in the interval of every 1000 milliseconds.

Math operators in JavaScript: You may wonder but JavaScript is educated enough to calculate things. In addition, it uses ‘+’ operator, likewise for subtraction, multiplication, and division it uses ‘ — ’, ‘ * ’ and ‘/’ operator respectively. JavaScript is able to calculate the reminder also, for that, it uses ‘%’ operator. ‘++’ is used for increment the data by 1 whereas, ‘- -’ is used for decrement the data by 1.

using math operators

Note that ‘= ’ is an assignment operator. It is used to assign a value to a variable.

Here ‘data+=10’ is same as ‘data=data+10’ likewise, it follows up for ‘-’, ‘*’ and ‘/’ operators.

Conditional statements: conditional statements are used when we have to choose between the two routes base on some Boolean values. Those Boolean values depend upon certain conditions.

The keyword used for executing conditional statements are ‘if’ and ‘else’. In implementation ‘if’ keyword is followed by parenthesis. The parenthesis keeps a statement inside it, which has an output in Boolean. If that Boolean has positive response, the set of instructions in curly braces are executed otherwise the browser seek for ‘else’ statement. And if it exists, the set of instruction in a curly braces followed by the else statements is executed.

Implementation of the conditional statements

Don't worry about the double equal “==” sign. It is used for the comparison. In addition to that the following signs are generally used:

“<=” for less than or equal to
“>=” for greater than or equal to
“&&” is a conditional logical AND operator
“||” is the conditional logical OR operator

Switch statements: switch statements are used for avoid writing conditional statements many times. Let us learn the implementation by the example directly:

Implementation of the switch statement

the switch statement is followed by the parenthesis having the variable name (“books” in ex.) inside the switch statements there are cases. Each case is checked by the browser until it encounters the break statement.

Loop statements: loop is something which executes the set of the statements certain number of times. So instead of writing the codes several times, the loop can be employed for these.

For loop: for loop needs three statements. First, a “counter” variable is created to track the progress of the loop. Then the test expression usually checks whether the counter has reached some boundary yet. The third statement used to provide the details for updating of the counter variable.

While loop: while loop needs a test expression.

Do-while loop: do while loop also needs a test expression but its structure is different from while loop. Actually while loop looks for a test expression and if it is all okay, executes the set of statements framed inside it. but instead, do while loop used to execute the set of statements and then check the test expression, to know whether it has to continue on the loop or not? Simple enough!

Note that only do-while loop should be ended up with semi-colon

Event handler: An event handler is basically constructing a scope in a webpage for responding the user action. For example clicking a mouse. They can be placed in many locations.

On click event handler: this is used to construct a scope for responding on mouse click.

<body>
<script type=”text/javascript”>

</script>
<form>
<input type=”button” name=”you can touch it” onclick=”alert(‘this is dialouge box’); alert(‘second time!’);” />
</form>
</body>

Note that alert function uses the double quotation box but to avoid ambiguity single quotation is used here. On clicking the button, the statements on the “onClick” specifier will all execute.

Next thing to note down is that the event handlers are not just limited to form button but it can be implemented in many other locations.

On mouse over event handler: this is used to construct a scope for responding the hovering of mouse cursor over the specified element.

<body>
<script type=”text/javascript”>

</script>
<a href=”http://www.google.com" onMouseOver=”alert(‘this is a dialouge box’);”>crawl over me!</a>
</body>

On mouse out event handler: this is used to construct a scope to respond when the mouse cursor does not hover over the specified element.

<body>
<script type=”text/javascript”>

</script>
<a href=”http://www.google.com" onMouseOut=”alert(‘this is a dialouge box’);”>crawl over me!</a>
</body>

Now you know that event handler can be used in different locations. But in the body tags there are a few event handlers which are associated with the body tags. One of such is On load event handler. This is used to construct a scope to respond when the webpage is loaded.

Likewise, On unload event handler is used to construct a scope to respond when the webpage is unloaded or closed.

Objects: object is a data type which comprises different properties (in the form of variables) and functions. It encapsulates the properties and functions/methods. In other words, it creates the abstraction of the bunch of variables and functions.

Objects are either of built in type, which can be used directly or you can create an instance of an object.

Creating an instance of an object

Creating an instance of an object basically mean creating your own object manually. Creating own object manually, starts with creating a blueprint of an object. The blueprint construction is mainly carried out by a constructor function. For whole implementation of blueprint construction the script tags reside in the head tags.

To access the variable or a function/method from the object, the dot operator “ . ” is used.

Ex. document.write(nameOftheObject.nameOftheVariable)

“This” pointer is used to refer the object of the current object.

Keyword “new” is used while creating a new object on the specified blueprint. The parameters are passed as per the blueprint.

Can you guess the output??

Adding function/methods to the objects

Like I said before, the object can encapsulate the variable and function/methods.

For this specifically a function is constructed, which returns the required output using the pointer to the current object. The output is stored in one of the property of constructor function.

Note: while using the function (here yearsUntilRetire), it is operated like we did in function calling (with parenthesis)

Here also to access function from the object, the dot operator is used.

While declaring the function, usually there is no parameter required. Function is able to access all the information from the object through this pointer.

Built-in objects

we have been using the built in objects. Socked? You don't need to be. We have been using document.write(“stuff to be printed”); for a while. Actually document is an object and write is one of the function of that object. Document object used to refer the document which appears in the screen.

Object initializers

When there is a need to create many objects, say 100 objects, then it is good practice to create object through constructor function. But in case, when you need to create one or two or less number of objects, then the object initializers are the better way to proceed.

Object initializers are the easier way to implement to create an object instance. Instead of using constructor function objects are directly initialized thereby.

Implementation of the object initializers

Array: An array is basically a having a single variable storing multiple values. For example, you can have a variable which can store the name of all the students of your class.

Now the question arises, how would you access the name of a particular student specifically? To resolve this issue array indexing comes into play. Let's see how to implement these all in JavaScript.

Implementation of an array

Can you guess the output??

It is “will”, as array indexing always starts with zero.

Other ways to implement an array

a) The value can be initialized after defining the array:

b) Using an empty array and then initializing any number of elements in it:

Properties and methods of an array

Length: It is the property to find the number of elements of an array. Let’s see the implementation.

var characters= new Array(“el”,”mike”,”dustin”);
document.write(characters.length);

Concatenation: It is the method to pick all the elements of two different arrays and to put them together in a new array. Let’s see the implementation.

var a= new Array(“el”,”mike”,”dustin”);
var b= new Array(“lucas”,”maxx”,”will”);

var c= a.concat(b);

Note: here we concatenated variable b into variable a. So “el” will be the first element in variable c and “will” will be the last element. Likewise, we can also concatenate variable an into variable b.

Join: join is a method which can join all the elements of an array and enables us to store them in the form of string. It can take a parameter. That parameter is subjected to be filled between the elements of an array. If no parameter is passed, by default the comma is filled between the elements of an array to form a string.

var movies= new Array(“the shawshank redemption”, “good will hunting”, “fight club”);

var mov= movies.join(“ ”);
document.write(mov); //the shawshank redemption good will hunting fight club

Pop: pop is a method to remove the last element of an array. It does not alter any other property of an array but just removes the last element from it.

var movies= new Array(“the shawshank redemption”, “good will hunting”, “fight club”);
movies.pop();
document.write(movies[2]); // undefined

Push : push is just opposite of pop. It adds the elements in an array. Elements are added in the last.

var movies= new Array(“the shawshank redemption”, “good will hunting”, “fight club”);
movies.push(“memento”,”the pearl harbour”);

Reverse: reverse is a method to reverse the indexing of the elements of an array. In other words the first element becomes the last one and the last one becomes the first one.

var movies= new Array(“the shawshank redemption”, “good will hunting”, “fight club”);

movies.reverse( );

Sort: sort is a method to sort the elements of an array in alphabetical order.

var movies= new Array(“the shawshank redemption”, “good will hunting”, “fight club”);

movies.sort( );

Adding array elements using a loop

Elements in an array can be added using a loop. It is less complicated and you will require lesser number of codes.

Associative arrays

Instead of indexing the arrays with numbers, strings may be used to specify a particular element of an array.

var el= new Array();
el[“age”]=14;
el[“hairColor”]=”brown”;
el[“realName”]=”Jane hooper”;

document.write(“she is”+ el[“realName”]+ her age is “+el[“age”]);

Math object: math object is a built in object, having some properties and methods.

For example: The value of pi can be accessed using math object.

doucment.write(Math.PI);

Likewise, there is a method to calculate the square root of a number.

var n= prompt(“enter the number”,“”);

var ans= Math.sqrt(n);

alert(“square root of ”+n+“ is ”+ans);

For more properties and method of math object follow this link:

Date object: date objects are used to access the current time and date. Date objects are created with the new date( ) constructor.

Program to print the current time

Accessing forms: Whenever you create forms for your webpage, JavaScript automatically creates form objects. What if you are working with a webpage having many forms? As always, JavaScript has the answer. Forms are also having indexing from zero to n(say)

To access the particular form, you can use its indexing. Let’s see an example for the implementation.

Accessing the form

For avoiding the use of indexing, name can be used to access the elements of the form.

Data validation

Data validation is carried out by creating a function, which will check the validity of the particular data. The data can be accessed from the forms.

Let’s see a simple example where the JavaScript will verify the password length. It has to be at least of 8 characters.

JavaScript has a huge variety in itself. But for now we are done with the basics.

Hope you enjoyed!

--

--