BASICS OF JAVASCRIPT - A SIMPLE START TO JQUERY, JAVASCRIPT, AND HTML5 FOR BEGINNERS (2014

A SIMPLE START TO JQUERY, JAVASCRIPT, AND HTML5 FOR BEGINNERS (2014)

CHAPTER 3: BASICS OF JAVASCRIPT

Interaction is an important facet of any website. In order to connect with the audience in a better way, it is vital to add behaviour to the website. This can be as simple as buttons or as complex as animations. These tasks can be added using JavaScript, which is a web and programming language. This chapter introduces JavaScript and shall help you get started with JavaScript on an immediate basis.

Background

JavaScript is the preferred programming language for client side scripting. Contrary to popular belief, JavaScript is in no way related to Java. In fact, it finds resemblance to ECMAScript. Besides this, the only common thing between this programming language and other programming languages like C and C++ is that it uses curly braces. The international standard for JavaScript is given in ISO/IEC 16262 and ECMA-262 specification.

One of the most important features of this programming language is that it is untyped. In other words, specifying the type of a variable is not necessary for using it. For example, if you have assigned a string to a variable, you can later assign an integer to the same variable. Variables are declared using the keyword var.

Data and Expressions

Any program accesses, manipulates and represents data to the user. Data is available in different types and forms. This data can be easily decomposed into values. In JavaScript, data may be represented as a primitive value, object or function.

The data representation at the lowest level is known as primitive data type and includes null, undefined, number, string and Boolean.

Several built-in objects are defined in JavaScript. These entail the Object object, global object, Array object, Function object, Boolean object, String object, Math object, Number object, the RegExp object, Date object, Error object and JSON object.

Any object that is callable is called a function. It may also be referred to as a method if the function is associated with an object.

Data is produced by using expressions, which is a name given to any code that generates a value. It may be assigned a value directly or the value may be computed by substituting and computing an expression composed of operands and operators. It is important to note that an operand can be another expression as well.

Number Data Type

The number data type is a primitive data type and it is internally stored as a floating point number, which is a 64 bit, double precision number. This 64 bit field stores the sign, exponent and fraction. While the leftmost bit is reserved for sign, the bits 0 to 51 are reserved for storing the fraction and bits 52-62 are used for the exponent.

Because of memory limitation on the system, 253 is the highest integer that can be stored. It is important to note that integer calculations generate a precise value. However, fractional data calculation may give imprecise results. Therefore, these values have to be truncated.

In addition to numbers and strings, JavaScript also supports the use of the following special characters.

● undefined specifies that the value has not been assigned yet.

NaN stands for ‘Not a Number’

● -Infinity any number that is less than -1.7976931348623157E + 10308 is denoted by Infinity.

● Infinity - any number that exceeds the value 1.7976931348623157E + 10308 is denoted by Infinity.

String Data Type

A string can simply be described as a collection of characters. Whenever you declare character(s) within quotes, the system interprets as a string. Sample strings include:

‘Hello World!’

“Hello World!”

However, if you want to include quotes as characters in the string, then you must add ‘\’ before the character. Sample string:

‘You\’re Welcome’

“You\’re Welcome”

JavaScript also supports other escape sequences like \t for tab and \n for newline.

Boolean Data Type

The Boolean data type is a binary data type and return either true or false. These operators are commonly used to indicate results of comparisons. For example,

10 > 5 will give ‘true’ while 5 > 10 will give ‘false’.

Operations on Number data Type

In order to perform calculations, operators are used. JavaScript supports all the basic operators and the operator precedence is as follows:

● Addition and subtraction have the same precedence.

● Multiplication and division have the same precedence.

● The precedence of multiplication and division is higher than that of addition and subtraction.

● If an expression contains several operators of the same precedence, then the expression is evaluated from left to right.

In addition to the basic operators, JavaScript also supports modulo (%) operator. This operator performs division and returns the remainder as result. For example, 23%7 is equal to 2.

Unary Operators

While operators like addition and subtraction need to operands to execute, some operators require only one. An example of such operators is typeof, which returns the datatype of the data. For example, typeof 12 returns ‘number’. Please note that ‘+’ and ‘-‘ can also be used as unary operators. This is the case when they are used to specify the sign of a number.

Logical Operators

Three logical operators are available for use in JavaScript namely, Not (!), Or (||) and And (&&). The results of operations that involve these operators are Boolean (true or false). The results of these operations are computed in accordance with the following:

AND (&&)

Binary operator

Both the conditions must be true

OR (||)

Binary operator

At least one of the conditions must be true

NOT (!)

Unary operator

The value of the condition determined is complemented.

For example,

‘Red’ != ‘Blue’ && 5 > 1 = ‘true’

‘Red’ != ‘Blue’ && 5 < 1 = ‘false’

‘Red’ == ‘Blue’ && 5 < 1 = ‘false’

For conditional operators, JavaScript uses short-circuit evaluation. In other words, if the value of the first condition is computed to be ‘false’, the system does not evaluate the other condition and directly presents the result.

Writing Code in JavaScript

Any statement followed by a semicolon is referred to as a statement. This statement may or may not produce a value unlike expressions, which must inadvertently produce a value.

Variables

Manipulation of data is performed with the help of variables. Data is stored in the memory and a named reference to this memory location is called a variable. Any identifier is declared as a variable by preceding it with a keyword var. A sample declaration of a variable is:

var result;

This statement declares a variable result. You may also define the variable as you declare it using a statement like this:

var result = 0;

or

var result = 23*4+6;

Certain rules have to be followed while naming variables. These rules are as follows:

● A variable name can be a combination of numbers and characters.

● A variable name cannot start with a number.

● The only special characters allowed in variable names is underscore (_) and dollar sign($).

● There should not be any whitespace in the variable name. For example, ‘result value’ is not allowed.

● JavaScript keywords are reserved and cannot be used.

Please note that JavaScript, unlike HTML is case sensitive. Therefore VAL and val are two different variables. Also, it is recommended that the variable name should be such that it describes the purpose for which it is being used. For example, if we name a variable result, it is evident that this variable will contain the result value computed by the code.

Another convention used in JavaScript is to name variables such that the first letter of the variable name is lowercase. However, every subsequent word in variable name starts with a capital letter. An example of this is the variable name, arrayResult. Besides this, the use of underscore and dollar sign is discouraged. However, they are used in jQuery objects.

Environment

A complete set of variables and the values they contain form what is called the environment. Therefore, whenever you load a new webpage in the browser, you are creating a new environment. If you take the example of Windows 8, it creates an environment when an application starts and the same is destroyed when the application ends.

Functions

A set of statements that solve a purpose are referred to as a function. The purpose of using functions is code reuse. If your program uses functionality multiple times in the program, then it is implemented as a function, which can be called as and when required. Since, a function is to be called from within the code, parameters can be sent to the function from the code. Upon execution, the function returns a value to the calling function. The syntax for function declaration and definition is as follows:

function multiply(a, b){

return a*b;

}

The name of the function must always be preceded with the keyword function. The variables a and b are parameters passed into the function and the function return the value obtained by computing a*b. This is a simple function, but you can implement complex and large function depending upon the functionality desired.

Now that you have implemented the function, you must be wondering as to how the function is called. Here is an example:

var x=2;

var y=5

var c=multiply(x, y);

Here, x and y are arguments that the function multiply will receive as parameters.

JavaScript is a loosely typed language. What that means is that if you pass more arguments to a function than what it is expecting, the system simply uses the first n arguments required and discards the rest. The advantage of this functionality is that you can use already implemented functions and pass the extra argument to scale the function and add functionality to it. On the other hand, you will not be able to get any indication of error if you unintentionally pass the wrong number of arguments.

JavaScript also provides some built-in functions for interacting with the user. These functions are as follows:

● alert

This function raises an alert with a message and the system resumes operation after the user clicks on the OK button. Sample implementation:

alert(‘Alert message!’);

● prompt

This function presents a textbox to the user and asks him or her to give input. You can supply the default value in the presented textbox and the user can click on the OK button to accept that the value entered is correct. Sample implementation:

var result = prompt(‘Enter a value’, ‘default value’);

● confirm

This message gives the user the choice to OK or CANCEL an action. Sample implementation:

var result = confirm(‘Do you wish to proceed?’);

Function Scope

Each variable that you declare possesses a scope of operation, which is the function within which the variable has been declared. This is called the local scope. Unlike, many other languages, which define local scope by the curly braces within which the variable lies, JavaScript’s local scope is same as function scope.

In addition to this, JavaScript also supports the concept of global scope, in which variables can be declared global and thus, can be used anywhere in the program.

Nesting Functions

Functions can be nested at any level. In other words, a function can be called from within another function, which could have been called from a different function. However, it is important to note that the scope of variable is within the function in which they are declared.

Conversion of One Data Type to Another

The prompt function discussed in the previous function returns a string. However, you had asked the user to enter a number. In such a scenario, a string to number conversion may be required. In JavaScript, a variable can be converted from one type to another using the following functions:

● Number Function

This function converts the object supplied to it into number data type. However, if the function is unable to perform the conversion, NaN is returned.

● String Function

This function converts the object supplied to it into string data type.

Conditional Programming

While writing code, you will faced with several situation where you need to execute a different set of instructions if the condition is true and another set of instructions if the same is false.

if-else

In order to implement such scenarios, you can use the if-else construct.

Syntax:

If(condition)

{

//code

}

else

{

//code

}

Consider a scenario in which you ask the user to enter his or her age using prompt function. Now, you must validate if the age is a valid number, before performing any computation on the value supplied. This is an ideal scenario of implementing conditional programming. Sample implementation for this scenario is:

var userAge = prompt(‘Enter your age: ’, ‘’);

if(isNaN(userAge))

{

alert(‘Age entered is invalid!’);

}

else

{

//code

}

In this sample code, the if clause checks if the entered value is a number. If the condition is true, that is the object entered is not a number, the user is given an alert message. However, if the condition is false, the code for else is executed.

It is important to note here that for single statements, it is not necessary to use curly braces. The above mentioned code can also be written as:

var userAge = prompt(‘Enter your age: ’, ‘’);

if(isNaN(userAge))

alert(‘Age entered is invalid!’);

else

//code

However, it is a good practice to use curly braces as there is scope of adding additional code later on.

if-else if

Another conditional programming construct is if-else if construct. This construct allows you to declare multiple conditions and the actions associated with them. The syntax is:

if(condition)

{

//code

}

else if(condition)

{

//code

}

else

{

//code

}

Switch

Multiple else ifs can be implemented using this construct. The execution overhead is high for this conditional programming construct as conditions are sequentially checked for validity. As an alternative, another keyword, switch, is available, which implements multiple conditions in the form of a jump table. Therefore, the execution overhead for switch is lesser than that of if-else if.

Sample implementation:

var userChoice = prompt('Choose an alphabet: a, b, c', 'e');

switch (userChoice) {

case 'a':

alert('a chosen\n');

break;

case 'b':

alert('b chosen\n');

break;

case 'c':

alert('c chosen\n');

break;

default:

alert('None of the alphabets chosen\n');

break;

};

The switch construct matches that value entered by the user with the values presented in the cases. If a matching value is found, the case is executed. However, in case, none of the case values match the entered input, the default case is executed. Besides this, you can also use conditions in case values and the case for which the condition holds true is executed.

If you do not use the break statement after the code of a case, all the cases following the matching case will be executed. For example, if the user enters ‘b’ for the above example and there are no break statements after the case code, then the output will be:

b chosen

c chosen

None of the alphabets chosen

Also, it is a good practice to use a break statement in the default case as well.

Note:

If you wish to determine if a keyword has been assigned any value or not, you can use the following code:

if(c)

{

//code

}

else

{

//code

}

If the variable c has been assigned a not-null value, then the if condition is true and the corresponding code is executed. On the other hand, if the value of variable c is undefined or null, the code within the else construct is executed.

Note:

The value of the following conditions will always be true:

'' == 0

null == undefined

'123' == 123

false == 0;

Please note that JavaScript converts the type of the variable concerned for compatibility in comparisons.

However, if you want to compare both the value and type of two variables, then JavaScript provides another set of operators, === and !===. When the comparisons for the values mentioned in the above example are done using this operator, the resultant will always be false.

Implementing Code Loops

Looping is an important and commonly used construct of any programming language. You will be faced by several situations when you need to perform the same set of instructions, a given number of times. In order to implement this scenario, loops have to be used. Loop constructs available in JavaScript include for, while and do-while.

The while loop includes a condition and as long as the condition remains true, the loop continues to execute. The do – while loop is a modification of the while loop. If the condition in the while is false, the while loop will not execute at all. On the other hand, even if the while condition is false, the do-while loop executes at least once.

Syntax for while loop:

while(condition)

{

//code

}

Syntax for do-while loop:

do

{

//code

}

while(condition)

The last type of loop available in JavaScript is for loop. The for loop allows you to initialize the looping variable, check for condition and modify the looping variable in the same statement.

Syntax:

for(initialize; condition; modify)

{

//code

}

Sample code:

for(i=0; i<10; i=i+1)

{

//code

}

This loop will run 10 times.

Note:

1. If at any point in time, you wish the loop to break, you can use the break statement.

2. If you do not specify a condition or specify a condition that is always true, the loop will run infinitely.

Error Handling

Exceptions are expected to occur at several points in your code. Therefore, it is best to implement a mechanism that can help you deal with these exceptions and avoid crashing.

An exception can be described as an illegal operation or any condition that is unexpected and not ordinary. A few examples of exceptions include unauthorized memory access.

You can perform exception handling at your own level by validating the values of variables before performing any operations. for instance, before performing division, it is advisable to check if the value of the denominator is equal to zero. Any operation that involves division of a number by zero raises the divide-by-zero exception.

However, there are other situations that cannot be handled in this manner. For instance, if the network connection breaks abruptly, you cannot do anything to pre-emptively handle the situation. Therefore, for situations like these, try, catch and finally keywords are used.

The code that is expected to throw an exception is put inside the try block. This exception, upon its occurrence, is caught by the catch block, which executes code that is supposed to be executed immediately after an exception is caught. The catch may also be followed by the finally block, which performs the final cleanup. This block is executed after the execution of try and catch blocks.

Syntax:

try

{

//code

}

catch(exception name)

{

//code

}

finally

{

//code

}

Working with Objects

JavaScript allows user access to a number of existing objects. One of these objects is an array. This section discusses all the basics related to this chapter. Dealing with objects in JavaScript also includes creation and handling of customized objects. However, this topic shall be covered in the chapter on JavaScript and jQuery.

Arrays

A collection of similar objects that are sequenced contiguously are referred to as an array. This array is given a name and each element can be accessed using the indexer, in the following form:

Let arrName[] be an array of names. The element arrName[2] refers to the third element of the array.

An array can be created using the following three methods:

● Insertion of Items Using Indexer

An array can be created using the new keyword and then, elements can be added into the array by assigning values to independent elements of the array. The new keyword creates an instance of the object Array using the constructor for the same.

Sample implementation:

var arrName = new Array();

arrName [0] = ‘Jack’;

arrName [1] = 'Alex';

● Condensed Array

The second type of implementation also uses the new keyword. However, in this case, the values are assigned to the elements as arguments to the constructor of the Array object.

Sample implementation:

var arrName = new Array(‘Jack, ‘Alex’);

● Literal Array

In this type of array definition, values are provided within the square brackets.

Sample implementation:

var arrName = [ ‘Jack, ‘Alex’];

The advantage of using the first type of definition is that it allows you to assign values to the elements anywhere in the code. On the other hand, the second and third type of implementation requires you to have the exact list of elements with you beforehand.

There are some properties associated with all object. The one property that can come in handy to you is length, which is a read-only value and when called return the number of elements present in the array. You can use this property in loops and conditions.

Objects can also have their own functions. These functions are called methods. The methods available for Array include:

● concat

Returns an array, which is the concatenation of the two arrays supplied to it.

● indexOf

Finds the location of the element concerned in the array and returns the index of the same.

● join

This method concatenates all the values present in the array. However, all these values are separated by a comma by default. You can specify a delimiter of your choice as well.

● lastIndexOf

This method works similarly as indexOf. However, it performs the search from the last element of the array. Therefore, it returns the index of the last element that matches the specified criterion.

● pop

Removes the last element and returns its value.

● push

Adds the concerned element to the end of the array and returns the changed value of length.

● reverse

This method reverses the order of the array elements. The original array is modified by this method.

● shift

Removes and returns the first value. If the array is empty, then undefined is returned.

● slice

This method requires two arguments, start index and end index. A new array is created with elements same as the elements present at indexes (start index) and (end index – 1).

● sort

This method sorts the elements and modifies the original array.

● splice

This method removes and adds elements to the specified array. The arguments taken by this method are start index (index from where the system should start removing elements), number of elements to be removed and elements to be added. If the value passed for number of elements is 0, then no elements are deleted. On the other hand, if this value is greater than the size of the array, all elements from the start index to the end of the array are deleted.

● toString

This method creates a string, which is a comma separated concatenated string of all the elements present in the array.

● unshift

This method adds an element at the first location of the array and return the modified value of length.

● valueOf

This method returns a string, which is the concatenated, comma-separated string containing all the values present in the array.

Note:

1. When working with functions, you can pass the whole array (using the array name) or a particular element of the array (using array name[indexer]).

2. Array elements can be modified by accessing the element using the indexer. For example, arrName[1] = ‘Danny’; assigns the value ‘Danny’ to the second element of the array.

DOM objects

The primary objects that you need to access while building an application, are the DOM objects associated with it. This access is necessary for you to control and get notified about events that are occurring on the webpage.

The DOM is a representation of a hierarchy of objects. These objects can be accessed using the document variable, which is built-in. This variable references the DOM and performs a search, which may return an active or static NodeList. While the active NodeList contains a list of elements that keep changing, the static NodeList contains elements that do not change over time. Since the retrieval of the static NodeList takes longer, it is advisable to choose search methods that work with active NodeList.

The search methods available for DOM include:

● getElementById

This method returns a reference to the first element that has the specified ID.

● getElementsByTagName

This method returns the active NodeList, which has the specified tag name.

● getElementsByName

This method returns the active NodeList, which has the specified name. This is a preferred method for option buttons.

● getElementsByClass

This method returns the active NodeList, which has the specified class name. However, this method is not supported by Internet Explorer version 8 and earlier.

● querySelector

This method accepts CSS selector as parameter and return the first matched element. However, this method is not supported by Internet Explorer version 7 and earlier.

● querySelectorAll

This method accepts CSS selector as parameter and return all the matched elements. Therefore, it returns a static NodeList. However, this method is not supported by Internet Explorer version 7 and earlier.

Events

If you look at JavaScript as an engine, then events are what give it the required spark. Events can occur in two situations. The first type of events are those that occur during user interactions. A user may click an image or enter text. All these are classified as events. Besides this, changes in state of the system are also considered an event. For instance, if a video starts or stops, an event is said to have occurred. The DOM allows you to capture events and execute code for the same.

In JavaScript, events are based on the publish-subscribe methodology. Upon creation of an object, the developer can publish the events that are related to this object. Moreover, event handlers can be added to this object whenever it is used. The event handler function notifies the subscribed events that the event has been triggered. This notification includes information about the event like location of the mouse and key-presses, in addition to several other details relevant to the event.

Capturing events:

There may be situations when an event may be attached to a button click, which may lie inside a hyperlink. In this situation, there is nesting of elements. Therefore, the event, when triggered, is passed down the DOM hierarchy. This process is called event capturing. However, once the event has reached the element, this event is bubbled up the hierarchy. This process is called event bubbling. This movement of the event across the hierarchy gives the developer an opportunity to subscribe or cancel the propagation, on need basis.

Subscribing to event:

The function, addEventListener, can be used for the subscription process. This function requires three arguments, the event, the function that needs to be called for the event and a Boolean value that determines if the function will be called during the capture or bubble process (true – capture, false – bubble). Mostly, this value is set to false. This is the preferred method for subscription as it is mentioned in the W3C standard.

Sample Code:

var btn = document.getElementById('btnDownload');

btn.addEventListener('click', initiateDownload, false);

However, other methods also exist, which include giving an online subscription to the html tag. This subscribes the event to the bubble process. The advantage of using this method is that it is the oldest and most accepted method. therefore, you can be sure that this method will work, regardless of what browser you are using. Please see the tag below to understand how this can be done.

<button id='btnDownload' onclick='initiateDownload();' >Download</button>

You can also use the traditional subscription process that uses JavaScript for subscribing the event.

var btn = document.getElementById('btnDownload');

btn.onclick = initiateDownload;

Unsubscribing:

Events can be unsubscribed using the function, removeEventListener, which takes the same set of parameters as addEventListener. For the btn variable used in the previous example, this can be done in the following manner:

var btn = document.getElementById('btnDownload');

btn.removeEventListener('click', initiateDownload, false);

How to cancel propagation?

The function, stopPropagation, is used for performing this operation. This can be done in the following manner:

var btn = document.getElementById('btnDownload');

btn.addEventListener('click', initiateDownload, false);

function initiateDownload (e){

//download

e.stopPropagation();

}

How to prevent the default operation?

This can be done by using the function, preventDefault, in the following manner:

var hyperlink = document.getElementById('linkSave');

hyperlink.addEventListener('click', saveData, false);

function saveData(e){

//save data

e.preventDefault();

}

JavaScript also provides the this keyword, which can be used if you wish to access the event causing element, on a frequent basis.

Window Event Reference

The current browser window is represented by the window variable, which is an instance of the Window object. The following events are associated with this object:

● afterprint

● beforeonload

● beforeprint

● error

● blur

● haschange

● load

● message

● focus

● online

● offline

● pageshow

● pagehide

● redo

● popstate

● storage

● resize

● unload

● undo

Form Event Reference

The actions that occur inside an HTML form trigger the flowing events:

● change

● blur

● focus

● contextmenu

● forminput

● formchange

● invalid

● input

● submit

● select

Keyboard Event Reference

The keyboard triggers the following events:

● keyup

● keypress

● keydown

Mouse Event Reference

The mouse triggers the following events:

● click

● drag

● drop

● scroll

● dblclick

● dragenter

● dragstart

● dragend

● dragover

● dragleave

● mousemove

● mousedown

● mouseover

● mouseout

● mousewheel

● mouseup

Media Event Reference

Media elements like videos, images and audios also trigger events, which are as follows:

● canplay

● abort

● waiting

● durationchange

● canplaythrough

● ended

● emptied

● loadeddata

● error

● loadstart

● loadedmetadata

● play

● pause

● progress

● playing

● readystatechange

● ratechange

● seeking

● seeked

● suspend

● stalled

● volumechange

● timeupdate