Introduction to JavaScript
Consider an organization that provides a Web site that allows its customers to view their products. The company has received frequent customer feedbacks to provide the shopping facility online. Therefore, the company has decided to add the shopping facility in their Web site by creating dynamic Web pages. These Web pages will allow the user to shop for the products online. Here, the main task of the developer is to validate the customer’s inputs while they shop online.
For example, details such as credit card number, email, and phone number entered by the customer must be in a proper format. Further, the developer also needs to retrieve the chosen products and their quantity to calculate the total cost.
The developer can handle all these critical tasks by using a scripting language. A scripting language refers to a set of instructions that provides some functionality when the user interacts with a Web page.
Scripting
Scripting refers to a series of commands that are interpreted and executed sequentially and immediately on occurrence of an event. This event is an action generated by a user while interacting with a Web page. Examples of events include button clicks, selecting a product from a menu, and so on. Scripting languages are often embedded in the HTML pages to change the behavior of the Web pages according to the user’s requirements.
There are two types of scripting languages. They are as follows:
- Client-side Scripting
Refers to a script being executed on the client’s machine by the browser. - Server-side Scripting
Refers to a script being executed on a Web server to generate dynamic HTML pages.
JavaScript
JavaScript is a scripting language that allows you to build dynamic Web pages by ensuring maximum user interactivity.
JavaScript language is an object-based language, which means that it provides objects for specifying functionalities. In real life, an object is a visible entity such as a car or a table. Every object has some characteristics and is capable of performing certain actions. Similarly, in a scripting language, an object has a unique identity, state, and behavior. The identity of the object distinguishes it from the other objects of the same type. The state of the object refers to its characteristics, whereas the behavior of the object consists of its possible actions.
The object stores its identity and state in fields (also called variables) and exposes its behavior through functions (actions).
Versions of JavaScript
The first version of JavaScript was developed by Brendan Eich at Netscape in 1995 and was named JavaScript 1.0. Netscape Navigator 2.0 and Internet Explorer 3.0 supported JavaScript 1.0. Over the period, it gradually evolved with newer versions where each version provided better features and functionalities as compared to their previous versions.
Client-side JavaScript
JavaScript is a scripting language, which can be executed on the client-side and on the server-side. A client-side JavaScript (CSJS) is executed by the browser on the user’s workstation. A client-side script might contain instructions for the browser to handle user interactivity. These instructions might be to change the look or content of the Web page based on the user inputs. Examples include displaying a welcome page with the username, displaying date and time, validating that the required user details are filled, and so on.
A JavaScript is either embedded in an HTML page or is separately defined in a file, which is saved with • js extension. In client-side scripting, when an HTML is requested, the Web server sends all the required files to the user’s computer. The Web browser executes the script and displays the HTML page to the user along with any tangible output of the script.
Server-side JavaScript
A server-side JavaScript (SSJS) is executed by the Web server when an HTML page is requested by a user. The output of a server-side JavaScript is sent to the user and is displayed by the browser. In this case, a user might not be aware that a script was executed on the server to produce the desirable output.
A server-side JavaScript can interact with the database, fetch the required information specific to the user, and display it to the user. This means that server-side scripting fulfills the goal of providing dynamic content in Web pages. Unlike client-side JavaScript, HTML pages using server-side JavaScript are compiled into bytecode files on the server.
Compilation is a process of converting the code into machine-independent code. This machine-independent code is known as the bytecode, which is an executable file. The Web server runs this executable to generate the desired output.
<Script> Tag
The <script> tag defines a script for an HTML page to make them interactive. The browser that supports scripts interprets and executes the script specified under the < script > tag when the page loads in the browser. You can directly insert a JavaScript code under the «script > tag. You can define multiple<script> tags either in the ‹head> or in the ‹body> elements of an HTML page. In HTML5, the type attribute specifying the scripting language is no longer required as it is optional.
Code Snippet 1 demonstrates the use of the < script> tag.
Example
DOCTYPE html>
<html>
<head>
‹script>
document.write ("Welcome to the Digital World"):
</script>
</head>
‹body>
...
</ body>
</html>
There are two main purposes of the < script › tag, which are as follows:
Identifies a given segment of script in the HTML page
Loads an external script file
Variables in JavaScript
A variable refers to a symbolic name that holds a value, which keeps changing. For example, age of a student and salary of an employee can be treated as variables. A real life example for variables includes the variables used in algebraic expressions that store values.
In JavaScript, a variable is a unique location in the computer’s memory that stores a value and has a unique name. The name of the variable is used to access and read the value stored in it. A variable can store different types of data such as a character, a number, or a string. Therefore, a variable acts as a container for saving and changing values during the execution of the script.
Declaring Variables
Declaring a variable refers to creating a variable by specifying the variable name. For example, you can create a variable named studName to store the name of a student. Here, the variable name studName is referred to as an identifier. In JavaScript, the var keyword is used to create a variable by allocating memory to it. A keyword is a reserved word that holds a special meaning in JavaScript.
You can initialize the variable at the time of creating the variable or later. Initialization refers to the task of assigning a value to a variable. Once the variable is initialized, you can change the value of a variable as required.
Variables allow keeping track of data during the execution of the script. While referring to a variable, you are referring to the value of that variable. In JavaScript, you can declare and initialize multiple variables in a single statement.
The syntax demonstrates how to declare variables in JavaScript.
Syntax:
var < variableName>;
where,
var: Is the keyword in JavaScript. variableName: Is a valid variable name.
The syntax demonstrates how to initialize variables in JavaScript.
Syntax:
‹variableName > = ;
where,
=: Is the assignment operator used to assign values.
value: Is the data that is to be stored in the variable.
The syntax demonstrates how to declare and initialize multiple variables in a single statement, which are separated by commas.
Syntax:
var ‹ variableNamel> = ‹valuel›, ‹variableName2> = <value2›;
Code Snippet declares two variables namely, studID and studName and assign values to them.
Example
var studID;
var studName;
studID = 50;
studName = "David Fernando”;
This code assigns values to studID and studName variables by using the assignment operator (=). The value named David Fernando is specified within double quotes.
Code Snippet demonstrates how to declare and initialize multiple variables in a single statement in JavaScript.
var studName - David, studAge - 15;
Variable Naming Rules
You cannot refer to a variable until it is created in JavaScript. JavaScript is a case-sensitive language. This means that if you specify x and x as variables, both of them are treated as two different variables. Similarly, in JavaScript, there are certain rules, which must be followed while specifying variables names. These rules for a variable name are as follows:
- Can consist of digits, underscore, and alphabets.
- Must begin with a letter or the underscore character.
- Cannot begin with a number and cannot contain any punctuation marks.
- Cannot contain any kind of special characters such as +, *,%, and so on.
- Cannot contain spaces.
- Cannot be a JavaScript keyword.
It is recommended to give meaningful names to variables such that the name determines the kind of data stored in the variable.
Data Types in JavaScript
A Web page designer can store different types of values such as numbers, characters, or strings in variables. However, the Web page designer must know what kind of data a particular variable is expected to store. To identify the type of data that can be stored in a variable, JavaScript provides different data types.
A Web page designer need not specify the data type while declaring variables. Due to this, JavaScript is referred to as the loosely typed language. This means that a variable holding a number can also hold a string value later. The values of variables are automatically mapped to their data types when the script is executed in the browser.
Data types in JavaScript are classified into two broad categories namely, primitive and composite data types. Primitive data types contain only a single value, whereas the composite data types contain a group of values.
Primitive Data Types
A primitive data type contains a single literal value such as a number or a string. A literal is a static value that you can assign to variables.
Lists the Primitive data type:
boolean
Contains only two values namely, true or false
null
Contains only one value namely, null. A variable of this value specifies that the variable has no value. This null value is a keyword and it is not the same as the value, zero
number
Contains positive and negative numbers and numbers with decimal point. Some of the valid examples include 6, 7.5, -8, 7.5-3, and so on
string
Contains alphanumeric characters in single or double quotation marks. The single quotes is used to represent a string, which itself consists of quotation marks. A set of quotes without any characters within it is known as the null string
Composite Data Types
A composite data type stores a collection of multiple related values, unlike primitive data types. In JavaScript, all composite data types are treated as objects. A composite data type can be either predefined or user-defined in JavaScript.
lists the composite data types.
Objects
Refers to a collection of properties and functions. Properties specify the characteristics and functions determine the behavior of a JavaScript object
Functions
Refers to a collection of statements, which are instructions to achieve a specific task
Arrays
Refers to a collection of values stored in adjacent memory locations
Methods
JavaScript allows you to display information using the methods of the document object.
The document object is a predefined object in JavaScript, which represents the HTML page and allow managing the page dynamically. Each object in JavaScript consists of methods, which fulfills a specific task. There are two methods of the document object, which displays any type of data in the browser. These methods are as follows:
→ write (): Displays any type of data.
→ writeln (): Displays any type of data and appends a new line character.
The syntax demonstrates the use of document. write () method, which allows you to display information in the displayed HTML page.
Syntax:
document. write (“<data>” + variables) ;
where,
data: Specifies strings enclosed in double quotes.
variables: Specify variable names whose value should be displayed on the HTML page.
The syntax demonstrates the use of document. writeln () method, which appends a new line character.
Syntax:
document writeln (“<data>”+ variables) ;
Using Comments
A Web page designer might code complex script to fulfill a specific task. In JavaScript, a Web page designer specifies comments to provide information about a piece of code in the script. Comments describe the code in simple words so that somebody who reads the code can understand the code. Comments are small piece of text that makes the program more readable. While the script is executed, the browser can identify comments as they are marked with special characters and do not display them.
JavaScript supports two types of comments. These are as follows:
→ Single-line Comments
Single-line comments begin with two forward slashes (//). You can insert single-line comments as follows:
// This statement declares a variable named num.
var num;
→ Multi-line Comments
Multi-line comments begin with a forward slash followed by an asterisk (/*) and end with an asterisk followed by a forward slash (*/). You can insert multiple lines of comments as follows:
/* This line of code
declares a variable */
var num;
Escape Sequence Characters
An escape sequence character is a special character that is preceded by a backslash (). Escape sequence characters are used to display special non-printing characters such as a tab space, a single space, or a backspace. These non-printing characters help in displaying formatted output to the user to maximize readability.
The backslash character specifies that the following character denotes a non-printing character. For example, \ t is an escape sequence character that inserts a tab space similar to the Tab key of the keyboard. In JavaScript, the escape sequence characters must always be enclosed in double quotes.
There are multiple escape sequence characters in JavaScript that provides various kind of formatting.
Events
Consider a scenario where you want to design an Employee registration Web form. This form allows the users to fill in the appropriate details and click the submit button. When the user clicks the submit button, the form data is submitted to the server for validation purposes. In this case, when the user clicks the button, an event is generated. The submission of form refers to the action performed on click of the button.
An event occurs when a user interacts with the Web page. Some of the commonly generated events are mouse clicks, key strokes, and so on. The process of handling these events is known as event handling.
Event Handling
Event handling is a process of specifying actions to be performed when an event occurs. This is done by using an event handler. An event handler is a scripting code or a function that defines the actions to be performed when the event is triggered.
When an event occurs, an event handler function that is associated with the specific event is invoked. The information about this generated event is updated on the event object.
The event object is a built-in object, which can be accessed through the window object. it specifies the event state, which includes information such as the location of mouse cursor, element on which an event occurred, and state of the keys in a keyboard
Event Bubbling
Event bubbling is a mechanism that allows you to specify a common event handler for all child elements. This means that the parent element handles all the events generated by the child elements. For example, consider a Web page that consists of a paragraph and a table.
The paragraph consists of multiple occurrences of italic text. Now, you want to change the color of each italic text of a paragraph when the user clicks a particular button. Instead of declaring an event handler for each italic text, you can declare it within the P element. This allows you to apply colors for all the italic text within the paragraph. This helps in reducing the development time and efforts since it minimizes the code.
Life Cycle of an Event
An event’s life starts when the user performs an action to interact with the Web page. It finally ends when the event handler provides a response to the user’s action. The steps involved in the life cycle of an event are as follows:
- The user performs an action to raise an event.
- The event object is updated to determine the event state.
- The event is fired.
- The event bubbling occurs as the event bubbles through the elements of the hierarchy.
- The event handler is invoked that performs the specified actions.
Keyboard Events
Keyboard events are the events that occur when a key or a combination of keys are pressed or released from a keyboard. These events occur for all keys of a keyboard.
The different keyboard events are as follows:
- Onkeydown
Occurs when a key is pressed down. - Onkeyup
Occurs when the key is released. - Onkeypress
Occurs when a key is pressed and released.
Mouse Events
Mouse events occur when the user clicks the mouse button.
onmousedown
Occurs when the mouse button is pressed
onmouseup
Occurs when the mouse button is released
jQuery
jQuery is a short and fast JavaScript library developed by John Resig in 2006 with a wonderful slogan: Write less and do more. It simplified the client side scripting of HTML. jQuery also simplifies HTML files animation, event handling, traversing, and developing AJAX based Web applications. It helps in rapid Web application development. Query is designed for simplifying several tasks by writing lesser code. The following are the key features supported by jQuery:
- Event Handling: Query has a smart way to capture a wide range of events, such as user clicks a link, without making the HTML code complex with event handlers.
- Animations: Query has many built-in animation effects that the user can use while developing their Web sites.
- DOM Manipulation: Query easily selects, traverses, and modifies DOM by using the cross-browser open source selector engine named Sizzle.
- Cross Browser Support: Query has a support for cross-browser and works well with the following browsers:
Internet Explorer 6 and above- Firefox 2.0 and above
- Safari 3.0 and above
- Chrome
- Opera 9.0 and above
- Lightweight: Query has a lightweight library of 19 KB size.
- AJAX Support: Query helps you to develop feature-rich and responsive Web sites by using AJAX technologies.
- Latest Technology: Query supports basic Path syntax and CSS3 selectors.
1 Comment