Javascrpt_control statement__array_function_string

Download as pdf or txt
Download as pdf or txt
You are on page 1of 66

Javascript- Introduction, Variable,

Operators,String, Array,Function

Narendra Mohan
Assistant Professor
Department of Computer Engineering and Applications
GLA University Mathura
What is JavaScript ?
• Introduced by Brendan Eich, member of Netscape
company in 1995
• cross-platform object based scripting language
for client and server applications
• 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.
Advantages of JavaScript

• Less server interaction


• Immediate feedback to the visitors
• Increased interactivity
• Richer interfaces
Limitations of JavaScript

• Client-side JavaScript does not allow the


reading or writing of files.
• JavaScript cannot be used for networking
applications because there is no such support
available.
• JavaScript doesn't have any multithreading or
multiprocessor capabilities.
What is Java?
• Totally different
• A full programming language
• Much harder!
• A compiled language
• Independent of the web
• Sometimes used together
First javascript Code
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript” >
document.write("Hello World!")
</script>
</body>
</html>
comments
• Single line comment using //
• Multiline Comment using
/*
……….
……….
*/
Incompatible Browser
<html><body>
<script type = “JavaScript”>
<!-- hide this stuff from older browsers
….JavaScript statements………// end the hiding
comment
-->
</script>
</body>
</html>
Adding javascript
• way to include javascript in HTML file is as
follows:
1. Script in <head>...</head> section.
2. Script in <body>...</body> section.
3. Script in <body>...</body> and <head>...</head>
sections.
4. Script in an external file and then include in
<head>...</head> section.
Where to Put the JavaScript
• Scripts in the head section: Scripts to be executed
when they are called, or when an event is triggered, go
in the head section. When you place a script in the
head section, you will ensure that the script is loaded
before anyone uses it.
• Scripts in the body section: Scripts to be executed
when the page loads go in the body section. When you
place a script in the body section it generates the
content of the page.
• Scripts in both the body and the head section: You can
place an unlimited number of scripts in your
document, so you can have scripts in both the body
and the head section.
Adding External file
Save as Use_External_JS.html
<html> Save as External.js
<head>
<script language= "javascript" document.write("hello
src=“external.js"> world");
</script>
</head>
<body>
</body>
</html>
JavaScript Statements
<html>
<head><title>My Page</title></head>
<body>
<script language="JavaScript">

document.write('This is my first
JavaScript Page');

</script>
</body>
</html>
JavaScript Statements
<html>
<head><title>My Page</title></head>
<body>
<script language=“JavaScript">

document.write('<h1>This is my first 
JavaScript Page</h1>');

HTML written
</script> inside JavaScript
</body>
</html>
JavaScript Statements
<html>
<head><title>My Page</title></head>
<body>
<p>
<a href="myfile.html">My Page</a>
<br />
<a href="myfile.html"
onMouseover="window.alert('Hello');">
My Page</A>
</p>
JavaScript written
</body> An Event
inside HTML
</html>
Example Statements
<script language="JavaScript">
window.prompt('Enter your
name:',''); Another event
</script>

<form>
<input type="button" Value="Press"
onClick="window.alert('Hello');">
Note quotes: " and '
</form>
External JavaScript
External scripts are practical when the same code is
used in many different web pages.
JavaScript files have the file extension .js.

document.write(“Hello world”) is saved as


myScript.js

To use an external script, put the name of the script


file in the src (source) attribute of a <script> tag
<html><body>
<script src="myScript.js"></script>
</body></html>
Alert - Dialog Box
<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>
Confirmation - Dialog Box
<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 - Dialog 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>
Data Types:
• Primitive Types: The three primitive types, Boolean,
Number and String, are the simple building blocks of all
data in JavaScript. Each of the three primitive types has a
corresponding object that provides additional functionality.
• Boolean: has only two values(True and False), case
sensitive. (Note that null, undefined, or an empty string, is
interpreted as false and any other value is considered true.)
• Number: contain both floating-point numbers and integers
In fact, all numbers in JavaScript are stored as floating point
numbers even though we may treat them as integers.
• String: A string is a row (not an array) of single characters.
There are a few special characters, known as escape
sequences
Escape Sequence
• Escape Sequence Produces

\b Backspace
\t Horizontal tab
\n Line feed (new line)
\f Form feed
\” Double quote
\’ Single quote
\\ Backslash
Other Core Data Type:
• JavaScript also defines a number of other core types, Null, Undefined and
Object
Null and Undefined:
• JavaScript’s null value means that there is no data or known value, and it is
used as a placeholder in a variable to let us know there’s nothing useful in
there.
• Undefined is the value held by a declared variable that has not been
initialized to a value, or not yet set to hold any data. Although a newly
declared variable holds no data, it does not hold a null value, but instead
undefined.
Object:
• The real functionality of JavaScript comes from its native objects. While
the core of the language so far has allowed us to store data and change
the flow of code, native objects allow us to not just store a string, but also
manipulate, search and change it.
Variables:
• can be assigned to any data type without the need to first declare the
type, declare it with the word var. must start with either a letter or the
underscore character. Variable names are usually case sensitive in most
browsers.
Keywords in javascript
• Write 20 keywords
Variable
• Can be assigned to any data type without the
need to first declare the type
• Declared with var keyword
• Start with either a letter or the underscore
character
operators
Flow control statements
If else statements: 3. If (condition)
{
1. If (condition) statements
{ }
statements else if (another condition)
} {
statements
2. If (condition) }
{ else
statements {
} statements
else }
{
statements
}
While Loop
The while statement repeats a statement or block based on a condition. It syntax is:
while (condition)
{
statements or block
}
Eg
num=0;
while(true)
{
document.write(++num +’ ‘);
if (num>20)
{
break;
}
}
Do while
• the statement or block is always executed at least once
syntax
do
{
statements
}while (condition)

Example
num=0;
do{
document.write(++num +’ ‘);
if (num>20)
{
break;
}
} while(true)
For loop
for (initialize; condition; change)
{
statements
}
Switch statement
Break and Continue

• Appear inside a block that is the repeated of a for,


while, do…while or switch statement.
• Break causes any repetition to stop immediately with
no further repetitions.
• Continue causes the current repetition to stop
immediately, but the test for another repetition still
goes ahead.
String - example
<script type= “text/javaScript”>
var a = “These sentence”;
var italics_a = a.italics();
var b = “will continue over”;
var upper_b = b.toUpperCase();
var c = “three variables”;
var red_c = c.fontcolor(“red”);
var sentence = a+b+c;
var sentence_change = italics_a+upper_b+red_c;
document.write(sentence);
document.write(sentence_change);
</script>
Declaring Array
<html><body>
<script language = “javascript” type= “text/javascript”>
var myArray1 = new Array(2);
Var myArray = new Array();
myArray[0]= “car”
myArray[1]= “Bus”
myArray[2]= “van”
For(i in myArray)
{
document.write(myArray[i] + “<br>”)
}
</script></body></html>
Declaring array
<html>
<body>
<script language = “javascript” type= “text/javascript”>
Var myArray = new Array();
myArray[0]= “car”
myArray[1]= “Bus”
myArray[2]= “van”
Document.write(myArray.length + “<br>”)
</script>
</body>
</html>
Array methods
<html><body>
<script type= "text/javascript">
var myarray1= new Array("car","bus","van");
var myarray2= ["RAM","ROM","HARD DISK", "55"];
myarray3= myarray1.concat(myarray2);
for(i in myarray3)
{
document.write(myarray3[i] + "<br>");
}
</script>
</body>
</html> car
bus
van
RAM
ROM
HARD DISK
55
Array methods( Cont’d)
<html>
<body>
<script type= "text/javascript">
var myarray= new Array();
myarray[0]="car";
myarray[1]="bus";
myarray[2]="van";
document.write("Array String :" + myarray.join("$") +"<br>");
//slice-first parameter start position and end position exclude
document.write("Array Slice :" + myarray.slice(0,2) +"<br>");
document.write("Array Reversed :" + myarray.reverse()
+"<br>");
</script></body></html>
output
Array String :car$bus$van
Array Slice :car,bus
Array Reversed :van,bus,car
Array methods(cont’d)
<html><body>
<script type= "text/javascript">
var numList= [2,8,1,7,6,5,3,4];
document.write("Array Sorted :" + numList.sort() +"<br>");
document.write("Array Slice :" + numList.slice(1,4) +"<br>");
document.write("Array after slice:" + numList +"<br>");
document.write("Array replace:" + numList.splice(1,3,9,10,11)
+"<br>");
document.write("Array after splice:" + numList +"<br>");
</script>
</body></html>
output
Index 0 1 2 3 4 5 6 7( showing extra)
Array Sorted :1,2,3,4,5,6,7,8
Array Slice :2,3,4
Array after slice:1,2,3,4,5,6,7,8
Array replace:2,3,4
Array after splice:1,9,10,11,5,6,7,8
Array Methods- push and pop
<script type = "text/javascript">
var myarray=[1,2];
myarray.push(3,4);
myarray.unshift(8,9);
document.write(myarray + "<br>");
myarray.pop();
document.write(myarray + "<br>");
document.write(myarray.shift() + "<br>");
document.write(myarray.sort() + "<br>");
</script>
output
8,9,1,2,3,4
8,9,1,2,3
8
1,2,3,9
Multidimension array
<html><body>
<script type= "text/javascript">
var multiarray= [[1,2,3,4,5],[6,7,8,9,10]];
document.write(multiarray[1][3] +"<br>");
for(var i=0;i<multiarray.length;i++)
{ for(j=0;j<multiarray[i].length;j++)
{
document.write(multiarray[i][j] +"<br>");
}
}
</script></body></html>
output
9
1
2
3
4
5
6
7
8
9
10
Functions - example 1
<html>
<body>
<script type= "text/javascript">
function add(num1,num2)
{
return num1+ num2;
}
document.write("1+2=" + add(1,2) +"<br>");
</script>
</body> output:1+2=3
</html>
Functions - example 2
<html><body>
<script type= "text/javascript">
function addmany(a,b,c,d,e,f)
{
var i=1;
var sum= 0;
document.write("Arguments length = " + arguments.length +"<br>");
while(i<arguments.length)
{
sum=sum+arguments[i];
i++;
document.write("Sum of the arguments =" + sum +"<br>");
}
}
addmany(1,1,1,1,1,2);
</script></body></html>
output
Arguments length = 6
Sum of the arguments =1
Sum of the arguments =2
Sum of the arguments =3
Sum of the arguments =4
Sum of the arguments =6
Function local variable
<html>
<body>
<script type = "text/javascript">
function fun()
{
var greeting="hello";
greeting= greeting + "javascript"
document.write(greeting + "<br>");
}
fun();
document.write(greeting + "<br>");
</script>
</body>
</html>
output
Hellojavascript
And error message undefined greeting because
scope is local
Global variable without var keyword
<html><body>
<script type = "text/javascript">
var greeting="hello";
function fun()
{
greeting= "Hello javascript"
document.write(greeting + "<br>");
}
fun();
document.write(greeting + "<br>");
</script></body> Hello javascript </body> </html>
Output
Hello javascript
Hello javascript
Hello javascript
<html><body>
<script type = "text/javascript">
var greeting="hello from Global variable";
function fun()
{
var greeting= "Hello from local variable";
greeting = greeting + "????";
document.write(greeting + "<br>");
}
greeting = greeting + "!!!!!!!!!!!!!!!!!!!!";
fun();
document.write(greeting + "<br>");
</script></body></html>
output
Hello from local variable????
hello from Global variable!!!!!!!!!!!!!!!!!!!!
Unexpected behavior due to variable
hoisting
<html><body>
<script type = "text/javascript">
var greeting="hello from Global variable";
function fun()
{
//not able to find locationof greeting variable because var
//greeting is written after that. if we remove var keyowrd from
//next statement in there will not be any issue and output //beocome
//hello from Global variable
//hello from local variable
document.write(greeting + "<br>");
var greeting= "Hello from local variable";
}
fun();
document.write(greeting + "<br>");
</script></body></html>
output
Undefined
hello from Global variable
<html> Variable hoisting
<body>
<script type = "text/javascript">
var greeting="hello from Global variable";
function fun()
{
var greeting; //declaration moved to the top but not initialized
document.write(greeting + "<br>");
greeting= "Hello from local variable";
}
fun();
document.write(greeting + "<br>");
</script> output:
</body> undefined
</html> hello from Global variable
Braces do not create scope- Example1
<script type = "text/javascript">
var num= 100;
if(num > 10)
{
var otherNumber = num;
}
document.write(otherNumber + "<br>");
</script> output: 100
Example-2
<script type = "text/javascript">
var num= 15;
while(num>10)
{
var otherNumber = num;
num--;
}
document.write(otherNumber + "<br>");
</script>
output
10
Function- example 3
<html><body>
<script type = "text/javascript">
var test = 1;
function fun()
{
document.write(test + "<br>");
var test = 2 ;
document.write(test + "<br>");
return true;
}
fun();
document.write(test + "<br>");
</script></body></html>
output
undefined
2
1
//var test = 2 ;( if we comment)
1
1
1
//test=2;( if remove var)
1
2
2
Example –Background colour change
<HTML><body>
<script type=“text/javascript”>
function start()
{
document.body.style.backgroundColor="yellow“;
}
</script>
<form>
<input type="button" onclick="start()” value="start">
</form></body></html>
<script type=text/javascript>
functio
var a =prompt(“Enter the first number”);
var b =prompt(“Enter the first number”);
var sum;

var b = prompt(“Enter the second number”);


b = parseInt(b);

Switch()
{
Case ‘add’:
var sum;
sum= a+b;
alert(sum);
Break;
//document.body.style.backgroundColor="red";
}
function sub()
{
var a =prompt(“Enter the first number”);
var sub1;
a = parseInt(a);

var b = prompt(“Enter the second number”);


b = parseInt(b);

sub1= a-b;
alert(sub1);

//document.body.style.backgroundColor="yellow";
}
</script></head>
<body> <form>
<input type="button" onclick="()" value=“add">
<input type="button" onclick="stp()" value="sub">
</form></body></html>
Blinking of text
<html><head>
<script type = "text/javascript">
function blink()
{
document.getElementById("t1").innerHTML= "";
setTimeout("appear()",500);
}

function appear()
{
document.getElementById("t1").innerHTML= "Hello World";
setTimeout("blink()",500);
}
</script></head>
<body onload="blink()">
<p id= "t1"> Hello World </p>
</body></html>
Example – Text hiding and showing
<html><head>
<script type="text/javascript">
function demoHide()
{
document.getElementById("p2").style.visibility="hidden";
document.body.style.backgroundColor = "red";
}

function demoShow()
{
document.getElementById("p2").style.visibility="visible";
document.body.style.backgroundColor = "yellow";

setInterval(function(){ demoHide() }, 3000);


setInterval(function(){demoShow() }, 5000);
}
</script>
<body>
<h1 id="p2">Hello World!!</h1>
<input type="button" onclick="demoHide()" value="hide">
<input type="button" onclick="demoShow()" value="Show">
</body></html>
Thanks

You might also like