JavaScript Notes 1
JavaScript Notes 1
Introduction
JavaScript (JS) is a web programming language used with HTML and CSS.
Features of JavaScript
Advantages of JavaScript
Disadvantages of JavaScript
1
It has security issues being a client-side scripting language.
For example, a function can be called when an event occurs, like when the user clicks a button.
<html>
<head>
<script type = "text/javascript">
function abc()
{
document.write("CareerRide Info");
}
</script>
</head>
<body>
Click the button
<input type=button onclick="abc()" value="Click">
</body>
</html>
2
Output:
CareerRide Info
Example 2
<!DOCTYPE html>
<html><head>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
<body>
</body>
</html>
output
<html>
<body>
<script type="text/javascript">
document.write("CareerRide Info");
</script>
</body>
</html>
3
Output:
CareerRide Info
Example 2
<!DOCTYPE html>
<html>
<body>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph
changed.";
}
</script>
</body>
</html>
3. External File
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph
changed.";
}
External scripts are practical when the same code is used in many
different web pages. JavaScript files have the file extension .js.
4
<html>
<body>
<script type="text/javascript" src="abc.js">
</script>
</body>
</html>
Output:
CareerRide Info
<!DOCTYPE html>
<html>
<body>
<h2>External JavaScript</h2>
<script src="myScript.js"></script>
</body>
</html>
output
5
External JavaScript Advantages
Placing scripts in external files has some advantages:
Arithmetic Operators
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus (Reminder)
++ Increment
-- Decrement
Comparison Operators
6
Operator Description
== Equal To
!= Not Equal To
Assignment Operators
Operator Description
= Simple Assignment
Logical Operators
Operator Description
|| Logical OR
! Logical NOT
Bitwise Operators
Operator Description
| Bitwise OR
^ Bitwise XOR
˜ Bitwise NOT
7
<< Left Shift
Special Operators
Operator Description
VOID Does not return any value. Used to return a URL with no value.
What is a script?
The 'type' attribute indicates which script language you are using with the
type attribute.
8
<script language= “javascript”>
document.write(“TutorialRide”);
</script>
You can also specify the <script language> using the 'language' attribute.
JavaScript Variables
Example:
var a;
var b;
Example: var a, b;
Variable initialization
var a = 10;
var b = 20;
Variable Scope
1. Global Variable
Declaring a variable outside the function makes it a Global Variable.
Variable is accessed everywhere in the document.
<html>
<head>
<script type = "text/javascript">
9
count = 5; //Global variable
var a = 4; //Global variable
function funccount() // Function Declaration
{
count+=5; // Local variable
a+=4;
document.write("<b>Inside function Global Count:
</b>"+count+"<br>");
document.write("<b>Inside function Global A: </b>"+a+"<br>");
}
</script>
</head>
<body>
<script type="text/javascript">
document.write("<b>Outside function Global Count:
</b>"+count+"<br>");
document.write("<b>Outside function Global A: </b>"+a+"<br>");
funccount();
</script>
</body>
</html>
Output:
2. Local Variable
A variable declared within a function is called as Local Variable.
It can be accessed only within the function.
<html>
<head>
<script type="text/javascript">
10
function funccount(a) // Function with Argument
{
var count=5; // Local variable
count+=2;
document.write("<b>Inside Count: </b>"+count+"<br>");
a+=3;
document.write("<b>Inside A: </b>"+a+"<br>");
}
</script>
</head>
<body>
<script type="text/javascript">
var a=3, count = 0;
funccount(a);
document.write("<b>Outside Count: </b>"+count+"<br>");
document.write("<b>Outside A: </b> "+a+"<br>");
</script>
</body>
</html>
Output:
Inside Count: 7
Inside A: 6
Outside Count: 0
Outside A: 3
11
To access an HTML element, JavaScript can use
the document.getElementById(id) method.
Example
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>
</body>
</html>
Output
Changing the innerHTML property of an HTML element is a common way to display data in HTML.
Example
<!DOCTYPE html>
<html>
<body>
<script>
document.write(5 + 6);
</script>
12
</body>
</html>
Try it Yourself »
</body>
</html>
Try it Yourself »
The document.write() method should only be used for testing.
Example
<!DOCTYPE html>
<html>
<body>
<script>
window.alert(5 + 6);
</script>
</body>
</html>
Try it Yourself »
13
the window object. This also means that specifying
the window keyword is optional:
Example
<!DOCTYPE html>
<html>
<body>
<script>
alert(5 + 6);
</script>
</body>
</html>
Try it Yourself »
<script>
console.log(5 + 6);
</script>
</body>
</html>
Try it Yourself »
The only exception is that you can call the window.print() method
in the browser to print the content of the current window.
Example
14
<!DOCTYPE html>
<html>
<body>
</body>
</html>
Output
JavaScript Statements
❮ PreviousNext ❯
Example
var x, y, z; // Statement 1
x = 5; // Statement 2
y = 6; // Statement 3
z = x + y; // Statement 4
T ry it
Yourself »
JavaScript Programs
A computer program is a list of "instructions" to be "executed" by
a computer.
15
JavaScript Statements
JavaScript statements are composed of:
Example
document.getElementById("demo").innerHTML = "Hello
Dolly.";
Try it Yourself »
The statements are executed, one by one, in the same order as they
are written.
Semicolons ;
T ry it Yourself »
a = 5; b = 6; c = a + b;
Try it Yourself »
On the web, you might see examples without semicolons.
Ending statements with semicolon is not required, but highly
recommended.
16
JavaScript White Space
JavaScript ignores multiple spaces. You can add white space to your
script to make it more readable.
var x = y + z;
If a JavaScript statement does not fit on one line, the best place to
break it is after an operator:
Example
document.getElementById("demo").innerHTML =
"Hello Dolly!";
Try it Yourself »
Example
function myFunction() {
document.getElementById("demo1").innerHTML = "Hello
Dolly!";
document.getElementById("demo2").innerHTML = "How are
you?";
}
17
Try it Yourself »
In this tutorial we use 2 spaces of indentation for code blocks.
You will learn more about functions later in this tutorial.
JavaScript Keywords
Here is a list of some of the keywords you will learn about in this
tutorial:
Keyword Description
debugger Stops the execution of JavaScript, and calls (if available) the
debugging function
do ... while Executes a block of statements, and repeats the block, while a
condition is true
18
return Exits a function
JavaScript Syntax
JavaScript Values
Fixed values
Variable values
JavaScript Literals
The two most important syntax rules for fixed values are:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Numbers</h2>
19
<p>Number can be written with or without decimals.</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 10.50;
</script>
</body>
</html>
10.50
1001
Try it Yourself »
"John Doe"
'John Doe'
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Strings</h2>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 'John Doe';
</script>
</body>
</html>
Try it Yourself »
20
JavaScript Variables
var x;
x = 6;
Try it Yourself »
JavaScript Operators
(5 + 6) * 10
Try it Yourself »
var x, y;
x = 5;
y = 6;
Try it Yourself »
JavaScript Expressions
21
For example, 5 * 10 evaluates to 50:
5 * 10
Try it Yourself »
x * 10
Try it Yourself »
JavaScript Keywords
var x, y;
x = 5 + 6;
y = x * 10;
Try it Yourself »
JavaScript Comments
JavaScript Identifiers
22
In JavaScript, identifiers are used to name variables (and keywords,
and functions, and labels).
The rules for legal names are much the same in most programming
languages.
Hyphens:
Underscore:
23
Lower Camel Case:
JavaScript Comments
❮ PreviousNext ❯
Any text between // and the end of the line will be ignored by
JavaScript (will not be executed).
Example
<!DOCTYPE html>
<html>
<body>
24
<h1 id="myH"></h1>
<p id="myP"></p>
<script>
// Change heading:
document.getElementById("myH").innerHTML = "JavaScript
Comments";
// Change paragraph:
document.getElementById("myP").innerHTML = "My first
paragraph.";
</script>
</body>
</html>
This example uses a single line comment at the end of each line to
explain the code:
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Comments</h2>
<p id="demo"></p>
<script>
// Write y to demo:
document.getElementById("demo").innerHTML = y;
</script>
</body>
</html>
25
Multi-line Comments
Example
/*
The code below will change
the heading with id = "myH"
and the paragraph with id = "myP"
in my web page:
*/
<!DOCTYPE html>
<html>
<body>
<h1 id="myH"></h1>
<p id="myP"></p>
<script>
/*
The code below will change
the heading with id = "myH"
and the paragraph with id = "myP"
*/
document.getElementById("myH").innerHTML = "JavaScript
Comments";
document.getElementById("myP").innerHTML = "My first
paragraph.";
</script>
</body>
</html>
26
Try it Yourself »
It is most common to use single line comments.
Block comments are often used for formal documentation.
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Comments</h2>
<h1 id="myH"></h1>
<p id="myP"></p>
<script>
//document.getElementById("myH").innerHTML = "My First
Page";
document.getElementById("myP").innerHTML = "My first
paragraph.";
</script>
</body>
</html>
.";
27
Try it Yourself »
Example
/*
document.getElementById("myH").innerHTML = "My First
Page";
document.getElementById("myP").innerHTML = "My first
paragraph.";
*/
Try it Yourself »
JavaScript Variables
❮ PreviousNext ❯
Example
var x = 5;
var y = 6;
var z = x + y;
Try it Yourself »
JavaScript Identifiers
28
Names can contain letters, digits, underscores, and dollar
signs.
Names must begin with a letter
Names can also begin with $ and _ (but we will not use it in
this tutorial)
Names are case sensitive (y and Y are different variables)
Reserved words (like JavaScript keywords) cannot be used as
names
This is different from algebra. The following does not make sense in
algebra:
x = x + 5
(It calculates the value of x + 5 and puts the result into x. The value
of x is incremented by 5.)
JavaScript variables can hold numbers like 100 and text values like
"John Doe".
JavaScript can handle many types of data, but for now, just think of
numbers and strings.
Example
var pi = 3.14;
var person = "John Doe";
var answer = 'Yes I am!';
29
Try it Yourself »
var carName;
carName = "Volvo";
You can also assign a value to the variable when you declare it:
Example
<p id="demo"></p>
<script>
var carName = "Volvo";
document.getElementById("demo").innerHTML = carName;
</script>
Try it Yourself »
It's a good programming practice to declare all variables at the
beginning of a script.
Start the statement with var and separate the variables by comma:
30
var person = "John Doe",
carName = "Volvo",
price = 200;
Try it Yourself »
Value = undefined
The variable carName will have the value undefined after the
execution of this statement:
Example
var carName;
Try it Yourself »
The variable carName will still have the value "Volvo" after the
execution of these statements:
Example
var carName = "Volvo";
var carName;
Try it Yourself »
JavaScript Arithmetic
Example
var x = 5 + 2 + 3;
Try it Yourself »
Example
var x = "John" + " " + "Doe";
Try it Yourself »
31
Also try this:
Example
var x = "5" + 2 + 3;
Try it Yourself »
If you put a number in quotes, the rest of the numbers will be
treated as strings, and concatenated.
Example
var x = 2 + 3 + "5";
Try it Yourself »
Example
var $$$ = "Hello World";
var $ = 2;
var $myMoney = 5;
Try it Yourself »
32
Example
var _lastName = "Johnson";
var _x = 2;
var _100 = 5;
Try it Yourself »
Create a variable called carName and assign the value Volvo to it.
Submit Answer »
JavaScript Operators
❮ PreviousNext ❯
Example
Assignment
var x = 10;
Try it Yourself »
Adding
var x = 5;
var y = 2;
var z = x + y;
33
Try it Yourself »
Multiplying
var x = 5;
var y = 2;
var z = x * y;
1. If Statement
if(condition)
{
//Statement 1;
//Statement 2;
}
<html>
<body>
<script type="text/javascript">
34
var num = prompt("Enter Number");
if (num > 0)
{
alert("Given number is Positive!!!");
}
</script>
</body>
</html>
Output:
2. If – Else Statement
if (condition)
{
//Statement 1;
}
else if(condition)
{
//Statement 2;
}
else
{
//Statement 3;
}
35
<html>
<head>
<script type="text/javascript">
var no = prompt("Enter a Number to find Odd or Even");
no = parseInt(no);
if (isNaN(no))
{
alert("Please Enter a Number");
}
else if (no == 0)
{
alert("The Number is Zero");
}
else if (no % 2)
{
alert("The Number is Odd");
}
else
{
alert("The Number is Even");
}
</script>
</head>
</html>
Output:
36
37
3. Switch Statement
Syntax
38
switch(expression)
{
case condition 1:
//Statements;
break;
case condition 2:
//Statements;
break;
case condition 3:
//Statements;
break;
.
.
case condition n:
//Statements;
break;
default:
//Statement;
}
<html>
<head>
<script type="text/javascript">
var day = prompt("Enter a number between 1 and 7");
switch (day)
{
case (day="1"):
document.write("Sunday");
break;
case (day="2"):
document.write("Monday");
break;
case (day="3"):
39
document.write("Tuesday");
break;
case (day="4"):
document.write("Wednesday");
break;
case (day="5"):
document.write("Thursday");
break;
case (day="6"):
document.write("Friday");
break;
case (day="7"):
document.write("Saturday");
break;
default:
document.write("Invalid Weekday");
break;
}
</script>
</head>
</html>
Output:
40
4. For Loop
For loop is a compact form of looping.
41
Flow Diagram of 'For' Loop
Syntax
<html>
<body>
<script type="text/javascript">
function palindrome()
{
var revstr = " ";
var strr = document.getElementById("strr").value;
var i = strr.length;
42
for(var j=i; j>=0; j--)
{
revstr = revstr+strr.charAt(j);
}
if(strr == revstr)
{
alert(strr+" - is Palindrome");
}
else
{
alert(strr+" - is not a Palindrome");
}
}
</script>
<form>
Enter a String or Number: <input type="text" id="strr"
name="checkpalindrome"><br>
<input type="submit" value="Check"
onclick="palindrome();">
</form>
</body>
</html>
Output:
43
5. For-in Loop
6. While Loop
Syntax
while (condition)
{
//Statements;
}
44
Example : Fibonacci Series Program using While Loop
<html>
<body>
<script type="text/javascript">
var no1=0,no2=1,no3=0;
document.write("Fibonacci Series:"+"<br>");
while (no2<=10)
{
no3 = no1+no2;
no1 = no2;
no2 = no3;
document.write(no3+"<br>");
}
</script>
</body>
</html>
Output:
7. Do-While Loop
45
Flow Diagram of Do – While
Syntax
do
{
//Statements;
}
while(condition);
<html>
<body>
<script type ="text/javascript">
var i = 0;
do
{
document.write(i+"<br>")
i++;
}
while (i <= 5)
46
</script>
</body>
</html>
Output:
0
1
2
3
4
5
8. Break Statement
47
Flow Diagram of Break Statement
9. Continue Statement
48
It takes some kind of appropriate action in response, such as writing to a
log, sending an error or recovery routine or sending a message.
The event handler may ultimately forward the event to an event
consumer.
Event Handler Description
onBlur It executes when the input focus leaves the field of a text, textarea or a select option.
onChange It executes when the input focus exits the field after the user modifies its text.
onClick In this, a function is called when an object in a button is clicked, a link is pushed, a check
an image map is selected. It can return false to cancel the action.
onFocus It executes when input focus enters the field by tabbing in or by clicking but not selecting
field.
onMouseOver The JavaScript code is called when the mouse is placed over a specific link or an object.
onMouseOut The JavaScript code is called when the mouse leaves a specific link or an object.
onReset It executes when the user resets a form by clicking on the reset button.
onSelect It executes when the user selects some of the text within a text or textarea field.
Event Handlers
<html>
<head>
<script type="text/javascript">
function time()
{
var d = new Date();
var ty = d.getHours() + ":"+d.getMinutes()+":"+d.getSeconds();
document.frmty.timetxt.value=ty;
49
setInterval("time()",1000)
}
</script>
</head>
<body onload="time()">
<center><h2>Displaying Time</h2>
<form name="frmty">
<input type=text name=timetxt size="8">
</form>
</center>
</body>
</html>
Output:
<html>
<body>
<script>
function validateform()
{
var uname=document.myform.name.value;
var upassword=document.myform.password.value;
if (uname==null || uname=="")
{
alert("Name cannot be left blank");
return false;
}
else if(upassword.length<6)
{
50
alert("Password must be at least 6 characters long.");
return false;
}
}
function emailvalidation()
{
var a=document.myform.email.value
if (a.indexOf("@")==-1)
{
alert("Please enter valid email address")
document.myform.email.focus()
}
}
</script>
<body>
<form name="myform" method="post" action="validpage.html"
onsubmit="return validateform()">
Email: <input type="text" size="20" name="email"
onblur="emailvalidation()"><br>
User Name: <input type="text" name="name"><br>
Password: <input type="password" name="password"><br>
<input type="submit" value="Submit" >
</form>
</body>
</html>
<html>
<body>
<script type="text/javascript">
alert("You are a Valid User !!!");
</script>
</body>
</html>
51
Output:
52
Flow Diagram of Continue Statement
53