0% found this document useful (0 votes)
10 views67 pages

Unit I Basics of Java Script Programming

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
10 views67 pages

Unit I Basics of Java Script Programming

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 67

UNIT I: BASICS OF JAVA SCRIPT

PROGRAMMING

MR. S. P. KHOLAMBE
LECTURER IN CO DEPTT.,
MET BKC IOTP NASHIK
Features of Java Script

 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 was first known as LiveScript, but Netscape changed its
name to JavaScript, possibly because of the excitement being
generated by Java. JavaScript made its first appearance in
Netscape 2.0 in 1995 with the name LiveScript. The general-
purpose core of the language has been embedded in Netscape,
Internet Explorer, and other web browsers.
2
Features of Java Script

3
Features of Java Script

1. JavaScript is a object-based scripting language.


2. Giving the user more control over the browser.
3. It Handling dates and time.
4. It Detecting the user's browser and OS,
5. It is light weighted.
6. JavaScript is a scripting language and it is not java.
7. JavaScript is interpreter based scripting language.
8. JavaScript is case sensitive.
9. JavaScript is object based language as it provides predefined objects.
10. Every statement in java script must be terminated with semicolon (;).
11. An important part of JavaScript is the ability to create new functions within
scripts. Declare a function in JavaScript using function keyword. 4
Uses of JavaScript

5
Limitations of JavaScript

 JavaScript have some limitation which is given below;


1. Client-side JavaScript does not allow the reading or writing of
files.
2. It cannot be used for networking applications because there
is no such support available.
3. It doesn't have any multithreading or multiprocessor
capabilities.
How To Write JavaScript Document?
 The java script can be directly embedded within the HTML documents
or it can be stored as external files.
 Syntax: <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.
 Type − This attribute is what is now recommended to indicate the
scripting language in use and its value should be set to
"text/javascript".
7
<html>
<body>
<script language = "javascript" type = "text/javascript">
<!--
document.write("Hello World!")
</script>
</body>
</html>

Output: It will display on Web Browser.

Hello World....!
Put JavaScript Code

 Three Places to put JavaScript code:


1. Between the body tag of html
2. Between the head tag of html
3. In .js file (external javaScript)

9
Between the body tag of html Between the head tag of html

<html> <html>
<body> <head>
<script type="text/javascript"> <script type="text/javascript">
document.write("Hello JavatScript"); function msg(){
</script> alert("Hello CSS");
</body> }
</html> </script>
</head>
<body>
<p>Welcome to Javascript</p>
<form>
<input type="button" value="click"
onclick="msg()"/>
</form>
</body>
</html>
External JavaScript file

message.js index.html

function msg() <html>


{ <head>
alert("Hello Javatpoint"); <script type="text/javascript" src="
} message.js"></script>
</head>
<body>
<p>Welcome to JavaScript</p>
<form>
<input type="button" value="click" o
nclick="msg()"/>
</form>
</body>
</html>
How To Write JavaScript Document?

 The JavaScript comments are meaningful way to deliver message.


It is used to add information about the code, warnings or
suggestions so that end user can easily interpret the code.
Comments in JavaScript:
1. The // is a single line comment.

2. The /*….. */ can be used as multi line comment.

12
Single Line Comment Multi Line Comment

<html> <html>
<body> <body>
<script> <script>
var a=1,b=20,c; /* It is multi line comment.
var c=a+b;//It adds values of a and b It will not be displayed */
variable document.write("Example of
document.write(c);//prints sum of 10 javascript multiline comment");
and 20 </script>
</script> </body>
</body> </html>
</html>
Output:
Output: It will display on Web Browser. Example of
21 javascript multiline comment
Object Name, Property, Method, Dot Syntax, Main Event

Object Name:
1. JavaScript is a OOP language.

2. Program are written using objects.

3. Object is nothing but a some entity. In JavaScript documents,


forms, fields, buttons are used object.
4. Each object is identified by ID or a name.

14
Object Name, Property, Method, Dot Syntax, Main Event

Property:
1. Property is actually a value associated with each object.

2. Each object has its own set of properties.

Methods:
1. It is a function associated with each object.

2. For the document object the method is write. It will display


message on browser.
15
Object Name, Property, Method, Dot Syntax, Main Event

Dot Syntax:
1. Every object is associated with property & methods.
2. For accessing the properties & methods of an object we use dot
operator.

Main Event:
1. Event is something happen when JavaScript execute.
2. Execution of appropriate code on occurrence of event is called event
handling.
3. Some function are defined for event handling. These function are called
event handler.
16
Values

JavaScript uses six types of values as follow:


1. Number: It contains integer & float.
2. String: String is collection of characters. It enclosed with single
or double quotes.
3. Boolean: It contain true & false type value.
4. Null: The null means no value.
5. Object: It is an entity that represents some value.
6. Function: It executes some task that generates output.

17
Variable

 A JavaScript variable is simply a name of storage location.


 There are two types of variables in JavaScript : local variable and global
variable.
 Variable in java script can store any type of value.
 var keyword are use before variable name to declare any variable.
 Syntax: var x;
Rules to declaring a variable:
1. Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar(
$ ) sign.
2. After first letter we can use digits (0 to 9), for example value1.
3. JavaScript variables are case sensitive, for example x and X are different
variables.
18
Variable

Local Variable:
 A JavaScript local variable is declared inside block or function.
It is accessible within the function or block only.

Global Variable:
 A JavaScript global variable is accessible from any function. A
variable i.e. declared outside the function or declared with
window object is known as global variable.

19
Local Variable
<html>
<body>
<script>
function abc()
{
var x=10;//local variable
document.write("Local Variable is: " ,x)
}
abc()
</script>
</body>
</html>

Output: It will display on Web Browser.


Local Variable is: 10
Global Variable
<html>
<body>
<script>
var d=200;//global variable
function a(){
document.writeln("Global variable in a():",d);
}
function b(){
document.writeln("Global variable in b():",d);
}
a();//calling function
b();
</script> </body> </html>

Output: It will display on Web Browser.


Keywords

A list of all the reserved words in JavaScript are given in the following table.
They cannot be used as JavaScript variables, functions, methods, loop labels, or
any object names.

22
Operators & Expression

 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.

1. Arithmetic Operators
2. Comparison Operators
3. Logical (or Relational ) Operators
4. Bitwise Operators
5. Assignment Operators
6. Conditional (or ternary) Operators
23
Arithmetic Operators

Assume variable A holds 10 and variable B holds 20, then −

24
<html> document.write("a / b = ");
<body> document.write(a / b);
<script type="text/javascript"> document.write(linebreak);

var a =43; document.write("a % b = ");


var b = 10; document.write(a % b);
var c = "Test"; document.write(linebreak);
var linebreak = "<br />";
a = ++a;
document.write("Arithmetic Operators"); document.write("++a = ");
document.write(linebreak); document.write(++a);
document.write("a + b = "); document.write(linebreak);
result = a + b;
document.write(result); b = --b;
document.write(linebreak); document.write("--b = ");
document.write(--b);
document.write("a - b = "); document.write(linebreak);
document.write(a - b);
document.write(linebreak); </script>
</body>
</html>
Comparison Operators
Assume variable A holds 10 and variable B holds 20, then −

26
<html> document.write("(a != b) : ", (a != b));
<body> document.write(linebreak);

<script type = "text/javascript"> document.write("(a >= b) : ", (a >= b));


var a = 10; document.write(linebreak);
var b = 20;
var linebreak = "<br />"; document.write("(a <= b) : ", (a <= b));
document.write(linebreak);
document.write("Comparison Operators"); </script>
document.write(linebreak); </body>
</html>
document.write("(a == b) : ", (a == b));
document.write(linebreak); Output:
Comparison Operators
document.write("(a < b) : ", (a < b)); (a == b) : false
document.write(linebreak); (a < b) : true
(a > b) : false
document.write("(a > b) : ", (a > b)); (a != b) : true
document.write(linebreak); (a >= b) : false
(a <= b) : true
Logical Operators
Assume variable A holds 10 and variable B holds 20, then −

28
<html>
<body> Output:
<script type="text/javascript"> Logical Operators:
var a = true; (a && b) : false
var b = false; (a || b) : true
var linebreak = "<br />"; !(a && b) : true

document.write("Logical Operators");
document.write(linebreak);

document.write("(a && b) : ", (a && b));


document.write(linebreak);

document.write("(a || b) : ", (a || b));


document.write(linebreak);

document.write("!(a && b) : ", (!(a && b)));


document.write(linebreak);

</script>
</body>
</html>
Bitwise Operators
Sr. No. Operator & Description
1 & (Bitwise AND)
It performs a Boolean AND operation on each bit of its integer arguments.
Ex: (A & B) is 2.
2 | (Bitwise OR)
It performs a Boolean OR operation on each bit of its integer arguments.
Ex: (A | B) is 3.
3 ^ (Bitwise XOR)
It performs a Boolean exclusive OR operation on each bit of its integer arguments.
Ex: (A ^ B) is 1.
4 ~ (Bitwise Not)
It is a unary operator and operates by reversing all the bits in the operand.
Ex: (~B) is -4.
5 << (Left Shift)
Ex: (A << 1) is 4.
6 >> (Right Shift)
Ex: (A >> 1) is 1.
7 >>> (Right shift with Zero)
30
Ex: (A >>> 1) is 1.
<html>
<body> document.write("(~b) : ", (~b));
document.write(linebreak);
<script type="text/javascript">
var a = 2; // Bit presentation 0010 document.write("(a << b) : ", (a << b));
var b = 3; // Bit presentation 0011 document.write(linebreak);
var linebreak = "<br />";
document.write("(a >> b) : ", (a >> b));
document.write("Bitwise Operator :"); document.write(linebreak);
document.write(linebreak); </script>
</body>
document.write("(a & b) : ",(a & b)); </html>
document.write(linebreak);
Output:
document.write("(a | b) : ", (a | b)); Bitwise Operator :
document.write(linebreak); (a & b) : 2
(a | b) : 3
document.write("(a ^ b) : ", (a ^ b)); (a ^ b) : 1
document.write(linebreak); (~b) : -4
(a << b) : 16
(a >> b) : 0
Assignment Operators

32
<html> document.write("Value of a => (a *=
<body> b) : ", (a *= b));
document.write(linebreak);
<script type="text/javascript">
var a = 33; document.write("Value of a =>
var b = 10; (a /= b) : ", (a /= b));
var linebreak = "<br />"; document.write(linebreak);

document.write("Value of a =>
document.write("Assignment Operators:");
(a %= b) : ", (a %= b));
document.write(linebreak);
document.write(linebreak);
</script>
document.write("Value of a => (a = b) : ", (a = b)); </body>
document.write(linebreak); </html>

document.write("Value of a => (a += b) : ", (a += b)); Output:


document.write(linebreak); Assignment Operators:
Value of a => (a = b) : 10
document.write("Value of a => (a -= b) : ", (a -= b)); Value of a => (a += b) : 20
document.write(linebreak);
Value of a => (a -= b) : 10
Value of a => (a *= b) : 100
Value of a => (a /= b) : 10
Value of a => (a %= b) : 0
Conditional (or ternary) Operators (? :)

 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.
<html>
<body>
<script type="text/javascript"> Output:
var a = 10; Conditional Operator:
var b = 20; ((a > b) ? 100 : 200) => 200
var linebreak = "<br />"; ((a < b) ? 100 : 200) => 100

document.write("Conditional Operator:");
document.write(linebreak);

document.write ("((a > b) ? 100 : 200) => ");


document.write((a > b) ? 100 : 200);
document.write(linebreak);

document.write ("((a < b) ? 100 : 200) => ");


document.write((a < b) ? 100 : 200);
document.write(linebreak);
</script>
</body>
typeof Operator
 The typeof operator is a unary  List of the return values for
operator that is placed before the typeof Operator.
its single operand, which can Type String Returned by
be of any type. Its value is a typeof
string indicating the data Number "number"
type of the operand.
String "string"
 The typeof operator evaluates
to "number", "string", or Boolean "boolean"
"boolean" if its operand is a Object "object"
number, string, or boolean Function "function"
value and returns true or false
based on the evaluation. Undefined "undefined"
Null "object"
<html>
<body>
Output:
<script type = "text/javascript">
typeof Operator:
var a = 10;
Result : B is String
var b = "String";
Result : A is Numeric
var linebreak = "<br />";

document.write("typeof Operator:")
document.write(linebreak);

result = (typeof b == "string" ? "B is String" : "B is Numeric");


document.write("Result : ", result);
document.write(linebreak);
result = (typeof a == "string" ? "A is String" : "A is Numeric");
document.write("Result : ",result);
document.write(linebreak);
</script> </body> </html>
If Statement

 JavaScript supports the following forms of if..else statement −


1. if statement
2. if...else statement
3. if...else if... statement.
If Statement

 The if statement is the fundamental control statement that allows


JavaScript to make decisions and execute statements conditionally.
 Syntax:
if (expression)
{
Statement(s) to be executed if expression is true
}
<html>
<body>
<script type = "text/javascript">
<!--
var age = 20;
if( age > 18 ) {
document.write("<b>Qualifies for driving</b>");
}
</script>
</body>
</html>

Output:
Qualifies for driving
If….else Statement

 The 'if...else' statement is the next form of control statement that allows
JavaScript to execute statements in a more controlled way.
 Syntax:
if (expression)
{
Statement(s) to be executed if expression is true
} else {
Statement(s) to be executed if expression is false
}
 If the resulting value is true, the given statement(s) in the ‘if’ block, are
executed. If the expression is false, then the given statement(s) in the else
block are executed.
<html>
<body>
<script type = "text/javascript">
<!--
var age = 15;
if( age > 18 ) {
document.write("<b>Qualifies for driving</b>");
} else {
document.write("<b>Does not qualify for driving</b>");
}
</script> Output:
</body> Does not qualify for driving
</html>
if...else if... statement

 The if...else if... statement is an advanced form of if…else that allows


JavaScript to make a correct decision out of several conditions.
 Syntax:
if (expression 1) {
Statement(s) to be executed if expression 1 is true
} else if (expression 2) {
Statement(s) to be executed if expression 2 is true
} else if (expression 3) {
Statement(s) to be executed if expression 3 is true
} else {
Statement(s) to be executed if no expression is true
}
<html> Output:
<body> Maths Book
<script type = "text/javascript">
var book = "maths";
if( book == "history" ) {
document.write("<b>History Book</b>");
} else if( book == "maths" ) {
document.write("<b>Maths Book</b>");
} else if( book == "economics" ) {
document.write("<b>Economics Book</b>");
} else {
document.write("<b>Unknown Book</b>");
}
</script>
</body>
<html>
Switch Case Statement

 The objective of a switch  Syntax:


statement is to give an
expression to evaluate and switch (expression) {
several different statements case condition 1: statement(s)
to execute based on the value break;
of the expression. case condition 2: statement(s)
break;
 The interpreter checks each
...
case against the value of the case condition n: statement(s)
expression until a match is break;
found. If nothing matches, a default: statement(s)
default condition will be used. }
<html> document.write("Exiting switch block");
<body> </script>
</body>
<script type = "text/javascript"> </html>
var grade = 3;
document.write("Entering switch block<br />");
switch (grade)
{ Output:
case 1: document.write("Good job<br />");
break;
Entering switch block
case 2: document.write("Pretty good<br />");
break; Passed
case 3: document.write("Passed<br />"); Exiting switch block
break;
case 4: document.write("Not so good<br />");
break;
case 5: document.write("Failed<br />");
break;
default: document.write("Unknown grade<br />")
}
Loop Statement

 The JavaScript loops are used to iterate the piece of code


using for, while, do while or for-in loops. It makes the code
compact. It is mostly used in array.
 There are four types of loops in JavaScript:
1. for loop
2. for-in loop
3. while loop
4. do-while loop
for Loop

 The 'for' loop is the most compact form of looping. It includes the
following three important parts −
1. The loop initialization where we initialize our counter to a starting
value. The initialization statement is executed before the loop begins.
2. The test statement which will test if a given condition is true or not. If
the condition is true, then the code given inside the loop will be
executed, otherwise the control will come out of the loop.
3. The iteration statement where you can increase or decrease your
counter.
 Syntax:
for (initialization; test condition; iteration statement)
{ Statement(s) to be executed if test condition is true }
<html>
<body>
<script type = "text/javascript">
<!--
var count;
Output:
document.write("Starting Loop" + "<br />");
for(count = 0; count < 10; count++) Starting Loop
{ Current Count : 0
Current Count : 1
document.write("Current Count : " + count ); Current Count : 2
document.write("<br />"); Current Count : 3
} Current Count : 4
document.write("Loop stopped!"); Current Count : 5
Current Count : 6
</script> Current Count : 7
</body> Current Count : 8
</html> Current Count : 9
Loop stopped!
For….in Loop

 The for...in loop is used to loop through an object's properties.


 Syntax:
for (variable name in object)
{
statement or block to execute
}
 In each iteration, one property from object is assigned to
variable name and this loop continues till all the properties of
the object are exhausted.
<html> Output:
Navigator Object
<body> Properties:
vendorSub
<script type = "text/javascript"> productSub
var aProperty; vendor
maxTouchPoints
document.write("Navigator Object Properties<br /> "); hardwareConcurrency
cookieEnabled
for (aProperty in navigator) appCodeName
{ appName
appVersion
document.write(aProperty); platform
product
document.write("<br />"); userAgent
} language
languages
document.write ("Exiting from the loop!"); onLine
doNotTrack
</script> geolocation
</body> mediaCapabilities
connection
</html> plugins
While Loop

 The purpose of a while loop is to execute a statement or code block


repeatedly as long as an expression is true. Once the expression becomes
false, the loop terminates.
 Syntax:
while (expression)
{
Statement(s) to be executed if expression is true
}
<html> Output:
Starting Loop:
<body> Current Count : 0
Current Count : 1
<script type="text/javascript"> Current Count : 2
var count = 0; Current Count : 3
Current Count : 4
document.write("Starting Loop: <br /> "); Current Count : 5
document.write("<br />"); Current Count : 6
Current Count : 7
while (count < 10) Current Count : 8
Current Count : 9
{ Loop stopped!
document.write("Current Count : " + count + "<br />");
count++;
}
document.write("Loop stopped!");
</script>
</body>
</html>
Do…while Loop
 The do...while loop is similar to the while loop except that the
condition check happens at the end of the loop.
 This means that the loop will always be executed at least once,
even if the condition is false.
 Syntax:
do {
Statement(s) to be executed;
} while (expression);
<html>
<body>
<script type = "text/javascript">
var count = 0;
document.write("Starting Loop" + "<br />");
do {
document.write("Current Count : " + count + "<br />");
count++;
} Output:
while (count < 5); Starting Loop:
Current Count : 0
document.write ("Loop stopped!"); Current Count : 1
</script> Current Count : 2
Current Count : 3
</body> Current Count : 4
</html> Loop stopped!
Break Statement

 The break statement, which was briefly introduced with the


switch statement, is used to exit a loop early, breaking out of the
enclosing curly braces.
<html>
<body> Output:
<script type="text/javascript">
var x = 0; Entering the loop:
1
document.write("Entering the loop: <br /> "); 2
while (x < 20) 3
{ 4
5
if (x == 5){ Exiting the loop!
break; // breaks out of loop completely
}
x = x + 1;
document.write( x + "<br />");
}
document.write("Exiting the loop!<br /> ");
</script>
</body> </html>
The Continue Statement

 The continue statement tells the interpreter to immediately


start the next iteration of the loop and skip the remaining code
block.
 When a continue statement is encountered, the program flow
moves to the loop check expression immediately and if the
condition remains true, then it starts the next iteration,
otherwise the control comes out of the loop.
<html>
<body> Output:
<script type = "text/javascript">
var x = 1; Entering the loop:
2
document.write("Entering the loop:<br /> ");
3
while (x < 10) 4
{ 6
x = x + 1; 7
if (x == 5) { 8
9
continue; // skip rest of the loop body
10
} Exiting the loop!
document.write( x + "<br />");
}
document.write("Exiting the loop!<br /> ");
</script>
</body>
</html>
Querying & Handling Properties

 It is the important feature of JavaScript is its interactivity with


the user.
 There are three types of popup box (Dialog Box) used in
JavaScript which the user can interact with the browser.
1. Alert Box
2. Confirm Box
3. Prompt Box
Alert Box

 An alert box is mostly used to give a warning message to the


users.
 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.
<html>
<head>
<script type = "text/javascript">
function Warn() {
alert ("This is a warning message Alert Box..!");
document.write ("This is a warning message by !");
}
</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>
Confirm Box

 A confirmation dialog box is mostly used to take user's consent


on any option. It displays a box with two buttons: OK and Cancel.
 If the user clicks on the OK button, the window method confirm()
will return true. If the user clicks on the Cancel button, then
confirm() returns false. You can use a confirmation dialog box as
follows.
<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>
Prompt Box

 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.
<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>

You might also like