JAVASCRIPT
JAVASCRIPT
Scripting Language
⦿ scaled down version of programming
language
⦿ usually interpreted by the computer (eg:
web browser )
⦿ Examples of script: Perl, VBScript and
JavaScript
⦿ Processing of a script :
⚫ Client-side : Interpreted by the web browser
⚫ Server-side : Interpreted by the web server
Javascript
⦿ It is not Java
⦿ Why use script?
⚫ Make a website more interactive and lively
⚫ To validate a form ( check for errors )
⚫ To do arithmetic operations
Javascript Example:
Javascript Example:
Javascript Declaration
<script language= “JavaScript”>
…
</script>
OR
<script type = “text /JavaScript”> ……
</script>
Hiding Javascript from Old
Browsers
<html>
<body>
<script type="text/javascript">
<!--
document.write("Hello World!");
//-->
</script>
</body>
</html>
Displaying Output
document.write
⦿ if (comparison)
{ statements; }
else
{ statements; }
⦿ if (comparison)
{ statements; }
else if (comparison)
{ statements; }
else
{ statements; }
if else example
<script language = “JavaScript”>
var marks;
marks = prompt(“Please type in your marks”);
marks = parseInt(marks);
if (marks>=50)
{
alert(“Pass”);
}
else if(marks < 50)
{
alert(“Fail”);
}
</script>
if else example
<script language = "JavaScript">
var marks;
marks = prompt("Please type in your Test 1 marks");
marks = parseInt(marks);
if (marks<0)
{alert("Your marks is out of range");}
else if (marks <50&&marks >0)
{ alert("You obtained E"); }
</body>
</html>
for loop example 2
<html>
<head><title>Looping</title></head>
<body>
<script language=“JavaScript”>
var i;
</body>
</html>
Nested for loop
<html>
<head>
<title>My First JavaScript</title>
</head>
<body>
<script language= "JavaScript">
for (a=0;a<3;a++)
{
document.write("<p>a is " + a + "</p>");
for (b=1;b<3;b++)
{
document.write("welcome " + b + "<br>" );
}
}
</script></body></html>
Explanation:
The outer for loop iterates 3 times (a=0 until a=2) while the
inner for loop iterates 2 times only (b=1 until b=2).
While loop
while (condition)
{
statements;
}
statement block;
do
{
statements;
}
while (condition);
do while example
<html>
<head>
<title>while loop</title>
</head>
<body>
<script language= "JavaScript">
var i=1;
do
{
document.write("i is " + i);
}
while (i>5)
document.write("<br>do while loop will execute
at least once");
</script></body></html>
do while VS while loop
do
{
document.write("i is " + i); while (i>5)
} {
while (i>5) document.write("i is " + i);
document.write("<br>do while loop }
will execute at least once"); document.write("<br>do while loop
will execute at least once");
Javascript Array
⦿ An array is a variable that can contain
multiple values
⦿ A variable is given array status using the
JS “new” keyword along with the JS
“Array()” constructor
⦿ Every item in an array has its own index
number. Index number starts with 0.
Array Declaration
⦿ EXAMPLE 1
}
</script>