Javascript: Client Side Scripting

You might also like

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

Client Side Scripting

• Run in the client browser and process requests without call backs to the server
• client-side scripting (JavaScript) benefits
• usability: can modify a page without having to post back to the server (faster
JavaScript UI)
• efficiency: can make small, quick changes to page without waiting for server
• event-driven: can respond to user actions like clicks and key presses
server-side scripting
• server-side programming (PHP,servlets,JSP,..) benefits:

• security: has access to server's private data; client can't see source code
• compatibility: not subject to browser compatibility issues
• power: can write files, open connections to servers, connect to databases, ...
SERVER-SIDE SCRIPTING CLIENT-SIDE SCRIPTING

Works in the back end which could not be visible at the Works at the front end and script are visible among the Java Script
client end. users.

• a lightweight scripting language


Processing Requires server interaction. Does not need interaction with the server.
• used to make web pages interactive
• insert dynamic text into HTML
PHP, servlets,JSP,AS>NET JavaScript, VB Script etc. • react to events
• Dynamic drop-down menus
• get information about client browser
Could effectively customize the web pages and provide Can reduce the load to the server. • form validation etc.
dynamic websites.
• JavaScript was created by Brendan Eich in 1995 during his time at Netscape Communications
• During the development phase it was known as Mocha, later it as livescript
Relatively secure. Insecure
• When it was released it as renamed as JavaScript
• JavaScript is casesensitive
• There are two ways to insert JavaScript code into an HTML code
JavaScript vs Java • Internal JavaScript:
• JavaScript code can be inserted either in head or body section of HTML using <script>
tag.
• The JavaScript programming language is developed by Netscape, Inc and not part of the Java
platform. <script type=“text/JavaScript” or language=“JavaScript”>
Java Script Code
• Java applications are run in a virtual machine or web browser while JavaScript is run on a web
browser. </script>
• External JavaScript:
• Java code is compiled whereas while JavaScript code is interpreted by webbrowser.
• We can create external JavaScript file with .js extension and embed it in many html pages.
• JavaScript is a scripting language, whereas Java is a programming language. <script type=“text/JavaScript” or language=“JavaScript” src=”js file path”>
Java Script Code
</script>
Note: The document.write() function is used to display
Internal java Script dynamic content through JavaScript.
<html>
<body>
JavaScript comments
<script language="javascript">
document.write("JavaScript is a simple language for javatpoint learners");
</script> • There are two types of comments in JavaScript.
</body>
</html>

• Single-line Comment
External java Script • // comment text
<html>
<head>
• Multi-line Comment
message.js <script type="text/javascript" src="message.js"></script> • /* comment
function msg(){ </head> ----
alert("Hello ,Welcome to VJIT"); <body>
<p>Welcome to JavaScript</p> */
}
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body>
</html>
Data Types
• JavaScript Variable:
• JavaScript is a dynamic type language
• variables are declared with the var keyword
• types are not specified
• There are two types of data types in JavaScript.
• Primitive data type
number🡪represents numeric values e.g. 100
<script type=text/javascript> boolean🡪represents boolean value either false or true
var x = 10; null🡪represents null i.e. no value at all
var y = 20;
var z=x+y;
• Non-primitive (reference) data type
document.write(z); • string🡪represents sequence of characters e.g. "hello"
</script> • Object🡪represents instance through which we can access members
Operator Description Example Operator Description Example
+ Addition 10+20 = 30 & Bitwise AND (10==20 & 20==33) = false
- Subtraction 20-10 = 10 | Bitwise OR (10==20 | 20==33) = false
* Multiplication 10*20 = 200 ^ Bitwise XOR (10==20 ^ 20==33) = false
/ Division 20/10 = 2 ~ Bitwise NOT (~10) = -10
% Modulus (Remainder) 20%10 = 0 << Bitwise Left Shift (10<<2) = 40
++ Increment var a=10; a++; Now a = 11 >> Bitwise Right Shift 10>>2) = 2
-- Decrement var a=10; a--; Now a = 9 >>> Bitwise Right Shift with Zero (10>>>2) = 2

Operator Description Example


&& Logical AND (10==20 && 20==33) = false
Operator Description Example
|| Logical OR (10==20 || 20==33) = false
== Is equal to 10==20 = false
! Logical Not !(10==20) = true
=== Identical (equal and of same type) 10==20 = false
!= Not equal to 10!=20 = true
!== Not Identical 20!==20 = false
> Greater than 20>10 = true
>= Greater than or equal to 20>=10 = true
< Less than 20<10 = false
<= Less than or equal to 20<=10 = false
Special Operastors
Operator Description JavaScript If-else
(?:) Conditional Operator returns value based on the condition. It is like if-else.
, Comma Operator allows multiple expressions to be evaluated as single statement.
delete Delete Operator deletes a property from the object.
in In Operator checks if object has the given property
instanceof checks if the object is an instance of given type if(expression1){
new creates an instance (object) //content to be evaluated if expression1 is true
typeof checks the type of object. if(expression){ }
void it discards the expression's return value. //content to be evaluated else if(expression2){
yieldchecks what is returned in a generator by the generator's iterator. } //content to be evaluated if expression2 is true
}
else if(expression3){
//content to be evaluated if expression3 is true
}
else{
if(expression){ //content to be evaluated if no expression is true
//content to be evaluated if condition is true }
}
else{
//content to be evaluated if condition is false
}
JavaScript switch JavaScript Loops

switch(expression){ There are four types of loops in JavaScript.


case value1:
code to be executed; for loop
break; while loop
case value2: do-while loop
code to be executed; for-in loop
break;
......

default:
code to be executed if above values are not matched; for (initialization; condition; increment/decrement)
} while (condition)
{
{
code to be executed
code to be executed
}
}
do{
JavaScript Popup Boxes
code to be executed
}while (condition);

• JavaScript has three kind of popup boxes:


• Alert box,
The for/in statement loops through the properties of an object(Associative arrays) • Confirm box, and
• Prompt box.
for (x in object)
{ • Alert Box
----
• An alert box is often used if you want to make sure information comes through to the user.
---
} • When an alert box pops up, the user will have to click "OK" to proceed.
for/of statement loops through the values of an iterable objects( window.alert("sometext");

for (variable of iterable) {


// code block to be executed
}
Functions
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. • A function is a set of statements that performs some tasks or does some computation and then returns the result to the user
• If the user clicks "OK", the box returns true. • In JavaScript functions are defined with the function keyword.
• If the user clicks "Cancel", the box returns false.
function functionName(parameters) {
// code to be executed
return expression; Example
window.confirm("sometext"); }
<html>
Prompt Box <script>
• A prompt box is often used if you want the user to input a value before entering a page. function msg(){
alert("hello! this is message");
• the user will have to click either "OK" or "Cancel" to proceed after entering an input value.
Document.writeln(“functions in JavaScript”);
• If the user clicks "OK" the box returns the input value.
}
• If the user clicks "Cancel" the box returns null.
</script>
window.prompt("sometext","defaultText"); <body onload="msg()">

</body>
</html>
//Passing Parameters and returning values

<html>
<script>
Arrays
function mul( a , b){
return a*b; The name of function in javascript is reference to the function
• array is an object that represents a collection of elements.
} body
document.write(mul(12,13)); This reference can be used to create other references also; var arrayname=[value1,value2.....valueN];
</script> <script> values are contained inside [ ] and separated by ,
<body > function mul( a , b){
return a*b;
} <html>
</body>
document.write(mul(12,13)); <body>
</html>
<script>
m=mul; var emp=[“Raj",“Ravi","Ram"];
document.write(m(10,12)); for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br/>");
</script> }
</script>
</body>
</html>
Using constructor Methods
Array Functions
concat() It returns a new array object that contains two or more merged arrays.
• Array() var res=array.concat(arr1,arr2,....,arrn) ;
• var array_name=new Array(); indexOf() It searches the specified element in the given array and returns the index of the first match.
• new keyword is used to create instance of array. var n=array.indexOf(element,index) ;
• Ex:
var emp = new Array();
emp[0] = “Raj"; join() It joins the elements of an array as a string.
var res=array.join(separator) ;// default separator is ,
emp[1] = “Ravi";
emp[2] = “Ram"; lastIndexOf() It searches the specified element in the given array and returns the index of the last match.
• Array(parameters) var n=array.lastIndexOf(element,index);
• var array_name=new Array(p1,p2,p3);
• Ex:
• var emp=new Array(“Raj",“Ravi",“Ram");
<html> pop() It removes and returns the last element of an array.
<body> var x=array.pop() ;
<script>
var arr1=["C","C++","Python"]; push() It adds one or more elements to the end of an array.
var arr2=["Java","JavaScript","Android"]; array.push(element1,element2....elementn)
var result=arr1.concat(arr2);
document.writeln(result+"<br>"); reverse() It reverses the elements of given array.
array.reverse()
var arr=["C","C++","Python","C++","Java"]; shift() It removes and returns the first element of an array.
var result= arr.indexOf("C++"); var n=array. shift();
document.writeln(result+"<br>");
unshift() It adds one or more elements in the beginning of the given array.
var arr=["PhP","Servlets","JSP"] array. unshift(e1,e2,....,en);
var result=arr.join(" ")
document.write(result+"<br>"); slice() It returns a new array containing the copy of the part of the given array.
array.slice(start,end)
var arr=["C","C++","Python","C++","Java"];
var result= arr.lastIndexOf("C++"); sort() It returns the element of the given array in a sorted order.
document.writeln(result+"<br>"); array.sort()
splice() It add/remove elements to/from the given array.
</script> array.splice(start,delete,element1,element2,----,elementn)

</body> elements can be deleted by using the JavaScript operator delete


</html> delete arra[index];
<html>
<body>
<script>
var arr=["AngularJS","Node.js","JQuery"];
document.writeln("Orginal array: "+arr+"<br>");
var arr=[2,4,1,8,5];
var result=arr.sort(); //1,2,4,5,8 Strings
document.writeln(result[0]+"<br>");
document.writeln("Extracted element: "+arr.pop()+"<br>");
document.writeln("Remaining elements: "+ arr+"<br>"); • String is an object that represents a sequence of characters
arr.push("PhP"); var arr=["Monday","Tuesday","Thursday","Friday"]; • 2 ways to create string in JavaScript
document.writeln("Remaining elements: "+ arr+"<br>"); var result=arr.splice(2,0,"Wednesday")
document.writeln(arr);
• var stringname="string value";
var rev=arr.reverse(); • var stringname=new String("string literal");
document.writeln(rev+"<br>"); </script>
</body>
var result=arr.shift(); </html>
document.writeln(result+"<br>");

var result=arr.unshift("J2EE");
document.writeln(arr+"<br>");

var result=arr.slice(0,2);
document.writeln("slice: "+result+"<br>");
Methods Description search() It searches a specified regular expression in a given string and returns its position if a match occurs.
charAt() It provides the char value present at the specified index. string.search(regexp)
var c=String.charAt(index) match() It searches a specified regular expression in a given string and returns that regular expression if a match
charCodeAt() It provides the Unicode value of a character present at the specified index. occurs.
var uc=string.charCodeAt(index) string.match(regexp)
replace() It replaces a given string with the specified replacement.

concat() It provides a combination of two or more strings. substr() It is used to fetch the part of the given string on the basis of the specified starting position and length.
var new_str=string.concat(str1,str2,...,strn) string.substr(start,length)

indexOf() It provides the position of a char value present in the given string. slice() It is used to fetch the part of the given string. It allows us to assign positive as well negative index.
var n=indexOf(ch[,position]) string.slice(start,end)
var n=indexOf(str[,position])
lastIndexOf() It provides the position of a char value present in the given string by searching a character from the last toString() It provides a string representing the particular object.
position. object.toString()
var n=lastIndexOf(ch[,position])
var n=lastIndexOf(str[,position])

toUpperCase() It converts the given string into uppercase letter.


var str=string.toUpperCase()
toLowerCase() It converts the given string into lowercase letter.
var str=string.toLowerCase()
var str="JavaScript is a scripting language. Scripting languages
<html> are often interpreted";
<body> document.writeln(str.search(/Scripting/g));

<script> var str="Javascript";


var str="JavaScript"; document.writeln(str.match(/a/g));
document.writeln("<br>"+str.charAt());//print first character
document.writeln("<br>"+str.charCodeAt(3));
var str="JavaScript";
var x="vidya "; document.writeln(str.substr(1,4));
var y=" Jyothi"; var str="JavaScript";
var z=" Inst. " document.writeln(str.substring(1,4));
</script>
document.writeln("<br>"+x.concat(y,z));
var web="Learn JavaScript on Javaworld";
document.write("<br>"+web.indexOf('a')); var str = "JavaScript";
document.write("<br>"+web.indexOf("Java")); document.writeln(str.slice(-5));
</body>
</html>

You might also like