JAVASCRIPT
--------------------------------------------------------------------------------------------------
Introduction:
JavaScript is the programming language of HTML and the Web. JavaScript is a very powerful client-
side scripting language. JavaScript is used mainly for enhancing the interaction of a user with the
webpage.
Javascript is a dynamic computer programming language. It is lightweight and most commonly used
as a part of web pages, whose implementations allow client-side script to interact with the user and
make dynamic pages. It is an interpreted programming language with object-oriented capabilities.
JavaScript can be implemented using JavaScript statements that are placed within the <script>...
</script>.
You can place the <script> tags, containing your JavaScript, anywhere within your web page, but it is
normally recommended that you should keep it within the <head> tags.
The <script> tag alerts the browser program to start interpreting all the text between these tags as
a script. A simple syntax of your JavaScript will appear as follows.
<script ...>
JavaScript code</script>
The script tag takes two important attributes −
Language − This attribute specifies what scripting language you are using. Typically, its value will be
javascript. Although recent versions of HTML (and XHTML, its successor) have phased out the use of
this attribute.
Type − This attribute is what is now recommended to indicate the scripting language in use and its
value should be set to "text/javascript".
So your JavaScript segment will look like −
<script language="javascript" type="text/javascript">
JavaScript code</script>
How to Run JavaScript?
Being a scripting language, JavaScript cannot run on its own. In fact, the browser is responsible for
running JavaScript code. When a user requests an HTML page with JavaScript in it, the script is sent
to the browser and it is up to the browser to execute it. The main advantage of JavaScript is that all
modern web browsers support JavaScript
Client-side JavaScript
Client-side JavaScript is the most common form of the language. The script should be included in or
referenced by an HTML document for the code to be interpreted by the browser.
Notes By:Prof.A.A.Anjikar,Dept of :EC, PCE
It means that a web page need not be a static HTML, but can include programs that interact with the
user, control the browser, and dynamically create HTML content.
The JavaScript client-side mechanism provides many advantages over traditional CGI server-side
scripts. For example, you might use JavaScript to check if the user has entered a valid e-mail address
in a form field.
The JavaScript code is executed when the user submits the form, and only if all the entries are valid,
they would be submitted to the Web Server.
JavaScript can be used to trap user-initiated events such as button clicks, link navigation, and other
actions that the user initiates explicitly or implicitly.
Advantages of JavaScript
1. JavaScript is a client side language
The JavaScript code is executed on the user’s processor instead of the web server thus it saves
bandwidth and load on the web server.
2. JavaScript is an easy language to learn
The JavaScript language is easy to learn and offers syntax that is close to English. It uses the DOM
model that provides plenty of predefined functionalities to the various objects on pages making it a
breeze to develop a script to solve a custom purpose.
3. JavaScript is comparatively fast for the end user
As the code is executed on the client side, results and processing is completed almost instantly
depending on the task (tasks in JavaScript on web pages are usually simple so as to prevent being a
memory hog) as it does not need to be processed in the site’s web server and sent back to the user
consuming local as well as server bandwidth.
4. Extended functionality to web pages
Third party add-ons like Greasemonkey enable JavaScript developers to write snippets of JavaScript
which can execute on desired web pages to extend its functionality. If you use a website and require
a certain feature to be included, you can write it by yourself and use an add-on like Greasemonkey
to implement it on the web page.
5. No compilation needed
JavaScript does not require compilation process so no compiler is needed. The browser interprets
JavaScript as it HTML tags.
6. Easy to debug and test
The understanding syntax of JavaScript is easy. Any person can learn it very easily and use it to
develop dynamic and scalable websites.
7. Platform independent
Notes By:Prof.A.A.Anjikar,Dept of :EC, PCE
Any JavaScript-enabled browser can understand and interpret JavaScript code. Any JavaScript code
can be executed on different types of hardware a JavaScript program written for.
8. Event-Based Programming language
Being an event-based language, different code segments are executed whenever a certain event
occurs in JavaScript. In simple language, a code segment is executed when a user clicks a button or
moves a mouse over the object.
9. Procedural programming capabilities
JavaScript language encompasses all the capabilities of a procedural language. Branching, looping,
condition checking are some of those capabilities that can be executed on a web page
Limitations of JavaScript
Client-side JavaScript does not allow the reading or writing of files. This has been kept for security
reason.
JavaScript cannot be used for networking applications because there is no such support available.
JavaScript doesn't have any multithreading or multiprocessor capabilities.
• Security Issues
Javascript snippets, once appended onto web pages execute on client servers immediately
and therefore can also be used to exploit the user's system. While a certain restriction is set
by modern web standards on browsers, malicious code can still be executed complying with
the restrictions set.
• Javascript rendering varies
Different layout engines may render Javascript differently resulting in inconsistency in terms
of functionality and interface. While the latest versions of javascript and rendering have been
geared towards a universal standard, certain variations still exist. Website Usability
Consultants all over the world make a living on these differences, but it enrages thousands
of developers on a daily basis.
•
Dialog Boxes(Popup box):
JavaScript supports three important types of dialog boxes. These dialog boxes can be used to raise
and alert, or to get confirmation on any input or to have a kind of input from the users.
1. Alert box
An alert dialog box is mostly used to give a warning message to the users. An alert box is often used
if you want to make sure information comes through to the user.
For example, if one input field requires to enter some text but the user does not provide any input,
then as a part of validation, you can use an alert box to give a warning message.
When an alert box pops up, the user will have to click "OK" to proceed.
E.g. 1
<html>
<body>
<h2>JavaScript Alert</h2>
Notes By:Prof.A.A.Anjikar,Dept of :EC, PCE
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
alert("I am an alert box!");
}
</script>
</body>
</html>
E.g 2
<html>
<head>
<script type="text/javascript">
<!--
function Warn() {
alert ("This is a warning message!");
document.write ("This is a warning message!");
}
//-->
</script>
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<input type="button" value="Click Me" onclick="Warn();" />
</form>
</body></html>
2. Confirm Box
A confirm box is often used if you want the user to verify or accept something.
When a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed.
If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns false.
E.g. 1
<html>
<body>
<h2>JavaScript Confirm Box</h2>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var txt;
if (confirm("Press a button!") == true) {
txt = "You pressed OK!";
} else {
Notes By:Prof.A.A.Anjikar,Dept of :EC, PCE
txt = "You pressed Cancel!";
}
document.getElementById("demo").innerHTML = txt;
}
</script>
</body>
</html>
E.g. 2
<html>
<head>
<script type="text/javascript">
<!--
function getConfirmation(){
var retVal = confirm("Do you want to continue ?");
if( retVal == true ){
document.write ("User wants to continue!");
return true;
}
else{
document.write ("User does not want to continue!");
return false;
}
}
//-->
</script>
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<input type="button" value="Click Me" onclick="getConfirmation();" />
</form>
</body></html>
3. Prompt Dialog Box
A prompt box is often used if you want the user to input a value before entering a page. The prompt
dialog box is very useful when you want to pop-up a text box to get user input. Thus, it enables you
to interact with the user. The user needs to fill in the field and then click OK.
This dialog box is displayed using a method called prompt() which takes two parameters: (i) a label
which you want to display in the text box and (ii) a default string to display in the text box.
This dialog box has two buttons: OK and Cancel. If the user clicks the OK button, the window method
prompt() will return the entered value from the text box. If the user clicks the Cancel button, the
window method prompt() returns null.
E.g. 1
<html>
<body>
Notes By:Prof.A.A.Anjikar,Dept of :EC, PCE
<h2>JavaScript Prompt</h2>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var txt;
var person = prompt("Please enter your name:", "Harry Potter");
if (person == null || person == "") {
txt = "User cancelled the prompt.";
} else {
txt = "Hello " + person + "! How are you today?";
}
document.getElementById("demo").innerHTML = txt;
}
</script>
</body>
</html>
E.g. 2
<html>
<head>
<script type="text/javascript">
<!--
function getValue(){
var retVal = prompt("Enter your name : ", "your name here");
document.write("You have entered : " + retVal);
}
//-->
</script>
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<input type="button" value="Click Me" onclick="getValue();" />
</form>
</body></html>
Operator in Javascript
Let us take a simple expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and ‘+’ is called
the operator. JavaScript supports the following types of operators.
Arithmetic Operators
Comparison Operators
Logical (or Relational) Operators
Notes By:Prof.A.A.Anjikar,Dept of :EC, PCE
Assignment Operators
Conditional (or ternary) Operators
Arithmetic Operators
Assume variable A holds 10 and variable B holds 20, then −
Sr.No Operator and Description
+ (Addition)
1
Adds two operands Ex: A + B will give 30
- (Subtraction)
2
Subtracts the second operand from the first Ex: A - B will give -10
* (Multiplication)
3
Multiply both operands Ex: A * B will give 200
/ (Division)
4
Divide the numerator by the denominator Ex: B / A will give 2
% (Modulus)
5
Outputs the remainder of an integer division Ex: B % A will give 0
++ (Increment)
6
Increases an integer value by one Ex: A++ will give 11
-- (Decrement)
7
Decreases an integer value by one Ex: A-- will give 9
The following code shows how to use arithmetic operators in JavaScript.
<html>
<body>
<script type="text/javascript">
<!--
var a = 33;
var b = 10;
var c = "Test";
var linebreak = "<br />";
document.write("a + b = ");
result = a + b;
document.write(result);
document.write(linebreak);
document.write("a - b = ");
result = a - b;
document.write(result);
document.write(linebreak);
document.write("a / b = ");
result = a / b;
document.write(result);
document.write(linebreak);
document.write("a % b = ");
result = a % b;
document.write(result);
document.write(linebreak);
document.write("a + b + c = ");
Notes By:Prof.A.A.Anjikar,Dept of :EC, PCE
result = a + b + c;
document.write(result);
document.write(linebreak);
a = ++a;
document.write("++a = ");
result = ++a;
document.write(result);
document.write(linebreak);
b = --b;
document.write("--b = ");
result = --b;
document.write(result);
document.write(linebreak);
//-->
</script>
Set the variables to different values and then try...
</body></html>
Output
a + b = 43
a - b = 23
a / b = 3.3
a%b=3
a + b + c = 43Test
++a = 35
--b = 8
Set the variables to different values and then try..
Comparison Operators
Assume variable A holds 10 and variable B holds 20, then −
Sr.No Operator and Description
= = (Equal)
1 Checks if the value of two operands are equal or not, if yes, then the condition becomes true.
Ex: (A == B) is not true.
!= (Not Equal)
Checks if the value of two operands are equal or not, if the values are not equal, then the
2
condition becomes true.
Ex: (A != B) is true.
> (Greater than)
Checks if the value of the left operand is greater than the value of the right operand, if yes, then
3
the condition becomes true.
Ex: (A > B) is not true.
< (Less than)
Checks if the value of the left operand is less than the value of the right operand, if yes, then
4
the condition becomes true.
Ex: (A < B) is true.
>= (Greater than or Equal to)
Checks if the value of the left operand is greater than or equal to the value of the right operand,
5
if yes, then the condition becomes true.
Ex: (A >= B) is not true.
Notes By:Prof.A.A.Anjikar,Dept of :EC, PCE
<= (Less than or Equal to)
Checks if the value of the left operand is less than or equal to the value of the right operand, if
6
yes, then the condition becomes true.
Ex: (A <= B) is true.
Logical Operators
Assume variable A holds 10 and variable B holds 20, then −
Sr.No Operator and Description
&& (Logical AND)
1 If both the operands are non-zero, then the condition becomes true.
Ex: (A && B) is true.
|| (Logical OR)
2 If any of the two operands are non-zero, then the condition becomes true.
Ex: (A || B) is true.
! (Logical NOT)
Reverses the logical state of its operand. If a condition is true, then the Logical NOT operator
3
will make it false.
Ex: ! (A && B) is false.
Bitwise Operators
Assume variable A holds 2 and variable B holds 3, then −
Sr.No Operator and Description
& (Bitwise AND)
1 It performs a Boolean AND operation on each bit of its integer arguments.
Ex: (A & B) is 2.
| (BitWise OR)
2 It performs a Boolean OR operation on each bit of its integer arguments.
Ex: (A | B) is 3.
^ (Bitwise XOR)
It performs a Boolean exclusive OR operation on each bit of its integer arguments. Exclusive
3
OR means that either operand one is true or operand two is true, but not both.
Ex: (A ^ B) is 1.
~ (Bitwise Not)
4 It is a unary operator and operates by reversing all the bits in the operand.
Ex: (~B) is -4.
<< (Left Shift)
It moves all the bits in its first operand to the left by the number of places specified in the
second operand. New bits are filled with zeros. Shifting a value left by one position is
5
equivalent to multiplying it by 2, shifting two positions is equivalent to multiplying by 4, and
so on.
Ex: (A << 1) is 4.
>> (Right Shift)
Binary Right Shift Operator. The left operand’s value is moved right by the number of bits
6
specified by the right operand.
Ex: (A >> 1) is 1.
>>> (Right shift with Zero)
7 This operator is just like the >> operator, except that the bits shifted in on the left are always
zero.
Notes By:Prof.A.A.Anjikar,Dept of :EC, PCE
Ex: (A >>> 1) is 1.
Assignment Operators
JavaScript supports the following assignment operators −
Sr.No Operator and Description
= (Simple Assignment )
1 Assigns values from the right side operand to the left side operand
Ex: C = A + B will assign the value of A + B into C
+= (Add and Assignment)
2 It adds the right operand to the left operand and assigns the result to the left operand.
Ex: C += A is equivalent to C = C + A
−= (Subtract and Assignment)
3 It subtracts the right operand from the left operand and assigns the result to the left operand.
Ex: C -= A is equivalent to C = C - A
*= (Multiply and Assignment)
4 It multiplies the right operand with the left operand and assigns the result to the left operand.
Ex: C *= A is equivalent to C = C * A
/= (Divide and Assignment)
5 It divides the left operand with the right operand and assigns the result to the left operand.
Ex: C /= A is equivalent to C = C / A
%= (Modules and Assignment)
6 It takes modulus using two operands and assigns the result to the left operand.
Ex: C %= A is equivalent to C = C % A
Conditional Operator (? :)
The conditional operator first evaluates an expression for a true or false value and then executes one
of the two given statements depending upon the result of the evaluation.
Sr.No Operator and Description
? : (Conditional )
1
If Condition is true? Then value X : Otherwise value Y
typeof Operator
The typeof operator is a unary operator that is placed before its single operand, which can be of any
type. Its value is a string indicating the data type of the operand.
The typeof operator evaluates to "number", "string", or "boolean" if its operand is a number, string,
or boolean value and returns true or false based on the evaluation.
Here is a list of the return values for the typeof Operator.
Type String Returned by typeof
Number "number"
String "string"
Boolean "boolean"
Object "object"
Function "function"
Undefined "undefined"
Null "object"
Notes By:Prof.A.A.Anjikar,Dept of :EC, PCE