SlideShare a Scribd company logo
JavaScript
SASIKUMAR M
Live as if you were to die tomorrow
Learn as if you were to Live forever
-Mahatma Gandhi
Introduction
• JavaScript is used to create client-side dynamic
pages.
• JavaScript is an object-based scripting
language which is lightweight and cross-platform.
• JavaScript is not a compiled language, but it is a
translated language.
• The JavaScript Translator (embedded in the
browser) is responsible for translating the
JavaScript code for the web browser.
Introduction
• JavaScript(JS) is a lightweight, interpreted
programming language.
• It is complimentary to and integrated with Java.
• JavaScript is very easy to implement because it is
integrated with HTML.
• 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
(1990) changed its name to JavaScript by Bredan Eich,
1995
• JavaScript is a case-sensitive language.
• JS to program the behavior of web pages
• Advantages of JavaScript
– Less server interaction − You can validate user input
before sending the page off to the server. This saves server
traffic, which means less load on your server.
– Immediate feedback to the visitors − They don't have to
wait for a page reload to see if they have forgotten to
enter something.
– Increased interactivity − You can create interfaces that
react when the user hovers over them with a mouse or
activates them via the keyboard.
– Richer interfaces − You can use JavaScript to include such
items as drag-and-drop components and sliders to give a
Rich Interface to your site visitors.
• 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.
Applications of Javascript
• JavaScript is used to create interactive websites.
• It is mainly used for:
– Client-side validation,
– Dynamic drop-down menus,
– Displaying date and time,
– Displaying pop-up windows and dialog boxes (like an
alert dialog box, confirm dialog box and prompt dialog
box),
– Displaying clocks etc.
3 Places to put JavaScript code
• Between the body tag of html
• Between the head tag of html
• In .js file (external javascript)
Example (<body>)
<body>
<script type="text/javascript">
alert("Hello, Welcome to Javascript");
</script>
</body>
Between the head tag of html
<html> <head>
<script type="text/javascript">
function msg() { alert("Hello Students, How R U? "); }
</script>
</head>
<body>
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body> </html>
External JavaScript file
• It provides code reusability because single
JavaScript file can be used in several html
pages
message.js
function msg() { alert("Hello"); }
Externaljs.html
<html> <head>
<script type="text/javascript" src="message.js"></script> </head>
<body>
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body> </html>
Comments
• Single-line Comment
// It is single line comment
• Multi-line Comment
/* It is multi line comment.
It will not be displayed */
Popup Boxes
• Alert Box – Warning message
• Confirm box – Yes/ No
• Prompt box – Reading value from user
Alert Box
<html> <head> <title> Alert Box </title> </head>
<body>
<h2>JavaScript Alert</h2>
<button onclick="myFunction()">Click</button>
<script type=“text/javascript”>
function myFunction() {alert("I am an alert box!");
}
</script> </body> </html>
Confirm box
<html> <head><title>Confirm box </title></head>
<body>
<h2>JavaScript Confirm Box</h2>
<button onclick="myFunction()">Click</button>
<p id="demo"></p>
<script type=“text/javascript”>
function myFunction() { var txt;
if (confirm("Press a button!")) {txt = "You pressed OK!"; }
else { txt = "You pressed Cancel!"; }
document.getElementById("demo").innerHTML = txt;
}
</script> </body> </html>
Prompt box
<html> <head> <title> Prompt box </title></head>
<body>
<h2>JavaScript Prompt</h2>
<button onclick="myFunction()">Click</button>
<p id="demo"></p>
<script type=“text/javascript”>
function myFunction() { var txt;
var person = prompt("Please enter your name:", “BSc");
if (person == null || person == "") {
txt = "User cancelled the prompt.";
} else { txt = "Hello " + person + "! How are you today?"; }
document.getElementById("demo").innerHTML = txt; }
</script> </body> </html>
JavaScript Variable
• A JavaScript variable is simply a name of storage location.
• Two types of variables : local variable and global variable.
• Rules for declaring a JavaScript variable (also known as identifiers).
– Name must start with a letter (a to z or A to Z), underscore( _ ), or
dollar( $ ) sign.
– After first letter, use digits (0 to 9)
– JavaScript variables are case sensitive, for example x and X are
different variables.
Local variable
• A JavaScript local variable is declared inside block or function. It is
accessible within the function or block only.
<script type=“text/javascript”>
function abc(){
var x=10; //local variable
}
</script>
Global variable
• Accessible from any function.
• A variable i.e. declared outside the function or declared with
window object is known as global variable.
Example
<script type=“text/javascript”>
var data=200; //global variable
function a(){
document.writeln(data);
}
function b(){
document.writeln(data);
}
a(); //calling JavaScript function
b();
</script>
Java Script Data Types
• Data types used to hold different types of values.
• Two types of data types
– Primitive data type
– Non-primitive (reference) data type
• JavaScript is a dynamic type language, means no need to
specify type of the variable because it is dynamically used
by JavaScript engine.
• To use var here to specify the data type. It can hold any
type of values such as numbers, strings etc. For example:
var a=40; //holding number
var b=”abcdef"; //holding string
Primitive Datatype
Data Type Description
String represents sequence of characters
e.g. "hello“
Number represents numeric values e.g. 100
Boolean represents boolean value either false
or true
Undefined represents undefined value
Null represents null i.e. no value at all
JavaScript non-primitive data types
Data Type Description
Object represents instance through which
we can access members
Array represents group of similar values
RegExp represents regular expression
Java Script Operators
• Arithmetic Operators
• Comparison (Relational) Operators
• Bitwise Operators
• Logical Operators
• Assignment Operators
• Special Operators
Arithmetic operator
Operator Description Example
+ Addition 10+20 = 30
- Subtraction 20-10 = 10
* Multiplication 10*20 = 200
/ Division 20/10 = 2
% Modulus (Remainder) 20%10 = 0
++ Increment var a=10; a++; Now a = 11
-- Decrement var a=10; a--; Now a = 9
JavaScript Comparison Operators
Operator Description Example
== Is equal to 10==20 = false
=== Identical (equal and of same
type) 10==20 = false
!= Not equal to 10!=20 = true
!== Not Identical20!==20 = false
> Greater than 20>10 = true
>= Greater than or equal to20>=10 = true
< Less than 20<10 = false
<= Less than or equal to 20<=10 = false
JavaScript Bitwise Operators
Operator Description Example
& Bitwise AND (10==20 & 20==33) = false
| Bitwise OR (10==20 | 20==33) = false
^ Bitwise XOR (10==20 ^ 20==33) = false
~ Bitwise NOT (~10) = -10
<< Bitwise Left Shift (10<<2) = 8
>> Bitwise Right Shift (negative number)
(10>>2) = 2
>>> Bitwise Right Shift with Zero (positive
number) (10>>>2) = 2
JavaScript Logical Operators
Operator Description Example
&& Logical AND (10==20 && 20==33)
= false
|| Logical OR (10==20 || 20==33)
= false
! Logical Not !(10==20) = true
JavaScript Assignment Operators
Operator Description Example
= Assign 10+10 = 20
+= Add and assign var a=10; a+=20; Now a 30
-= Subtract and assign var a=20; a-=10; Now a 10
*= Multiply and assign var a=5; a*=20; Now a 100
/= Divide and assign var a=10; a/=2; Now a = 5
%= Modulus and assign var a=10; a%=2; Now a = 0
JavaScript Special Operators
Operator Description
(?:) 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
New creates an instance (object) type of checks the type of
object.
Void it discards the expression's return value.
Yield checks what is returned in a generator by the
generator's iterator.
Conditional Statements
• Selection
– If Statement
– If else statement
– if else if statement
• Loop
– While
– Do-while
– For
– For-in
• Switch
– Multiway branch
IF Statement
• It evaluates the content only if expression is true.
• The signature of JavaScript if statement is given below.
if(expression){
//content to be evaluated
}
Example
<script type=“text/javascript”>
var a=20;
if(a>10){
document.write("value of a is greater than 10");
}
</script>
If...else Statement
• It evaluates the content whether condition is true
of false.
• The syntax of JavaScript if-else statement is given
below.
if(expression){
//content to be evaluated if condition is true
}
else{
//content to be evaluated if condition is false
}
Example
<script type=“text/javascript”>
var a=20;
if(a%2==0){
document.write("a is even number");
}
else{
document.write("a is odd number");
}
</script>
JavaScript If...else if statement
• It evaluates the content only if expression is true from several expressions.
• The signature of JavaScript if else if statement is given below.
if(expression1){
//content to be evaluated if expression1 is true
}
else if(expression2){
//content to be evaluated if expression2 is true
}
else if(expression3){
//content to be evaluated if expression3 is true
}
else{
//content to be evaluated if no expression is true
}
Example
<script type=“text/javascript”>
var a=20;
if(a==10){
document.write("a is equal to 10");
}
else if(a==15){
document.write("a is equal to 15");
}
else if(a==20){
document.write("a is equal to 20");
}
else{
document.write("a is not equal to 10, 15 or 20");
}
</script>
switch statement
• Used to execute one code from multiple
expressions.
• It is just like if..else..if statement that
discussed in previous slide.
• But it is convenient than if..else..if
• The signature of JavaScript switch statement is
given below.
Syntax
switch(expression){
case value1:
code to be executed;
break;
case value2:
code to be executed;
break;
......
default:
code to be executed if above values are not matched;
}
Example
<script type=“text/javascript”>
var grade='B'; var result;
switch(grade){
case 'A': result="A Grade"; break;
case 'B': result="B Grade"; break;
case 'C': result="C Grade"; break;
default: result="No Grade"; }
}
document.write(result);
</script>
while loop
• Iterates the elements for the infinite number of times.
• It should be used if number of iteration is not known.
• The syntax of while loop is given below.
while (condition)
{
code to be executed
}
Example
<script type=“text/javascript”>
var i=11;
while (i<=15)
{
document.write(i + "<br/>");
i++;
}
</script>
do while loop
• Iterates the elements for the infinite number
of times like while loop.
• But, code is executed at least once whether
condition is true or false.
• The syntax of do while loop is given below.
do{
code to be executed
}while (condition);
Example
<script type=“text/javascript”>
var i=21;
do{
document.write(i + "<br/>");
i++;
}while (i<=25);
</script>
For loop
• Iterates the elements for the fixed number of
times.
• It should be used if number of iteration is
known. The syntax of for loop is given below.
for (initialization; condition; increment)
{
code to be executed
}
Example
<script type=“text/javascript”>
for (i=1; i<=5; i++)
{
document.write(i + "<br/>")
}
</script>
for in loop
• To iterate the properties of an object.
Function
• JavaScript functions are used to perform operations.
• Call JavaScript function many times to reuse the code.
• Advantage of JavaScript function
– Code reusability: Call a function several times so it save coding.
– Less coding: It makes our program compact. No need to write
many lines of code each time to perform a common task.
Syntax
function functionName([arg1, arg2, ...argN])
{
//code to be executed
}
Example
<script type=“text/javascript”>
function msg(){
alert("hello! this is message");
}
</script>
<input type="button" onclick="msg()"
value="call function"/>
Function with Argument
<script type=“text/javascript”>
function getcube(number){
alert(number*number*number);
}
</script>
<form>
<input type="button" value="click"
onclick="getcube(4)"/>
</form>
Function with return value
<script type=“text/javascript”>
function getInfo(){
return "hello students! How r u?";
}
</script>
<form>
<input type="button" value="click"
onclick="getinfo()"/>
</form>
Array
• JavaScript Array is an object that represents a
collection of similar type of elements.
• 3 ways to construct array in JavaScript
– By array literal
– By creating instance of Array directly (using new
keyword)
– By using an Array constructor (using new keyword)
• JavaScript array literal
– var arrayname=[value1,value2.....valueN];
Example
<script type=“text/javascript”>
var stu=[“abc",“def",“ijk"];
for (i=0;i<stu.length;i++){
document.write(stu[i] + "<br/>");
}
</script>
• JavaScript Array directly (new keyword)
var arrayname=new Array();
<script type=“text/javascript”>
var i;
var stu = new Array();
stu[0] = “abc";
stu[1] = “cde";
stu[2] = “fgh";
for (i=0;i<stu.length;i++){
document.write(stu[i] + "<br>");
}
</script>
• JavaScript array constructor (new keyword)
<script type=“text/javascript”>
var stu=new Array(“abc",“cde",“fgh");
for (i=0;i<stu.length;i++){
document.write(stu[i] + "<br>");
}
</script>
JavaScript Array Methods
Methods Description
concat() It returns a new array object that contains two or more merged
arrays.
copywithin() It copies the part of the given array with its own elements and
returns the modified array.
every() It determines whether all the elements of an array are satisfying
the provided function conditions.
fill() It fills elements into an array with static values.
filter() It returns the new array containing the elements that pass the
provided function conditions.
find() It returns the value of the first element in the given array that
satisfies the specified condition.
findIndex() It returns the index value of the first element in the given array
that satisfies the specified condition.
forEach() It invokes the provided function once for each element of an
array.
includes() It checks whether the given array contains the specified element.
indexOf() It searches the specified element in the given array and returns
the index of the first match.
join() It joins the elements of an array as a string.
lastIndexOf() It searches the specified element in the given array
and returns the index of the last match.
map() It calls the specified function for every array element
and returns the new array
pop() It removes and returns the last element of an array.
push() It adds one or more elements to the end of an array.
reverse() It reverses the elements of given array.
shift() It removes and returns the first element of an array.
slice() It returns a new array containing the copy of the part
of the given array.
sort() It returns the element of the given array in a sorted
order.
splice() It add/remove elements to/from the given array.
unshift() It adds one or more elements in the beginning of the
given array.
Concat example
<script type=“text/javascript”>
var arr1=["C","C++","Python"];
var arr2=["Java","JavaScript","Android"];
var result=arr1.concat(arr2);
document.writeln(result);
</script>
Output
C,C++,Python,Java,JavaScript,Android
Array sort() method
• The JavaScript array sort() method is used to arrange the array
elements in some order.
• By default, sort() method follows the ascending order.
Example
<script type=“text/javascript”>
var arr=["AngularJS","Node.js","JQuery","Bootstrap"]
var result=arr.sort();
document.writeln(result);
</script>
Output
AngularJS,Bootstrap,JQuery,Node.js
slice() method
• Array slice() method extracts the part of the given array and returns it.
• This method doesn't change the original array.
array.slice(start,end)
• start - It is optional. It represents the index from where the method starts
to extract the elements.
• end - It is optional. It represents the index at where the method stops
extracting elements.
<script type=“text/javascript”>
var arr=["AngularJS","Node.js","JQuery","Bootstrap"]
var result=arr.slice(1,2);
document.writeln(result);
</script>
Output:
Node.js
indexOf() method
• Array indexOf() method is used to search the position
of a particular element in a given array.
• This method is case-sensitive.
• The index position of first element in an array is always
start with zero. If an element is not present in an array,
it returns -1.
array.indexOf(element,index)
• element - It represent the element to be searched.
• index - It represent the index position from where
search starts. It is optional.
Example
<script type=“text/javascript”>
var arr=["C","C++","Python","C++","Java"];
var result= arr.indexOf("C++");
document.writeln(result);
</script>
Output
1
join()
• Array join() method combines all the elements
of an array into a string and return a new
string.
• We can use any type of separators to separate
given array elements.
array.join(separator)
• Separator() - It is optional. It represent the
separator used between array elements.
Example
<script type=“text/javascript”>
var arr=["AngularJs","Node.js","JQuery"]
var result=arr.join('-')
document.write(result);
</script>
Output
AngularJs-Node.js-JQuery
reverse()
• Array reverse() method changes the sequence of elements of the
given array and returns the reverse sequence.
array.reverse()
Example
<script type=“text/javascript”>
var arr=["AngulaJS","Node.js","JQuery"];
var rev=arr.reverse();
document.writeln(rev);
</script>
Output
JQuery,Node.js,AngulaJS
every()
• The JavaScript array every() method checks whether all the given
elements in an array are satisfying the provided condition.
• It returns true when each given array element satisfying the
condition otherwise false.
<script type=“text/javascript”>
var marks=[50,40,45,37,20];
function check(value)
{
return value>30; //return false, as marks[4]=20
}
document.writeln(marks.every(check));
</script>
copyWithin()
• The JavaScript array copyWithin() method copies the part of the
given array with its own elements and returns the modified array.
• This method doesn't change the length of the modified array.
<script type=“text/javascript”>
var arr=["AngularJS","Node.js","JQuery","Bootstrap"]
// place at 0th position, the element between 1st and 2nd position.
var result=arr.copyWithin(0,1,2);
document.writeln(result);
</script>
Output:Node.js,Node.js,,Jquery,Bootstrap
Filter()
• The JavaScript array filter() method filter and extract the element of an
array that satisfying the provided condition.
• It doesn't change the original array.
<script type=“text/javascript”>
var marks=[50,40,45,37,20];
function check(value)
{
return value>30;
}
document.writeln(marks.filter(check));
</script>
Output: [50,40,45,37]
fill()
• The JavaScript array fill() method fills the elements of the given array with
the specified static values. This method modifies the original array.
• It returns undefined, if no element satisfies the condition.
<script type=“text/javascript”>
var arr=["AngularJS","Node.js","JQuery"];
var result=arr.fill("Bootstrap");
document.writeln(arr);
</script>
Output: Bootstrap, Bootstrap, Bootstrap
find()
• The JavaScript array find() method returns the
first element of the given array that satisfies the
provided function condition.
<script type=“text/javascript”>
var arr=[5,22,19,25,34];
var result=arr.find(x=>x>20);
document.writeln(result)
</script>
output:22
forEach()
• The JavaScript array forEach() method is used to invoke
the specified function once for each array element.
<script type=“text/javascript”>
var sum = 0;
var arr = [10,18,12,20];
arr.forEach(function myFunction(element) {
sum= sum+element;
document.writeln(sum);
});
</script>
string
• String is an object that represents a sequence of characters.
• There are 2 ways to create string in JavaScript
– By string literal
– By string object (using new keyword)
By string literal
var stringname="string value";
<script type=“text/javascript”>
var str=“Hi Welcome!";
document.write(str);
</script>
OUTPUT
Hi Welcome!
By string object (using new keyword)
• var stringname=new String("string literal");
<script type=“text/javascript”>
var stringname=new String
("hello javascript string");
document.write(stringname);
</script>
Output:
hello javascript string
String Methods
Methods Description
charAt() It provides the char value present at the specified index.
charCodeAt() It provides the Unicode value of a character present at the
specified index.
concat() It provides a combination of two or more strings.
indexOf() It provides the position of a char value present in the given
string.
lastIndexOf() It provides the position of a char value present in the given
string by searching a character from the last position.
search() It searches a specified regular expression in a given string
and returns its position if a match occurs.
match() It searches a specified regular expression in a given string
and returns that regular expression if a match occurs.
replace() It replaces a given string with the specified replacement.
substr() It is used to fetch the part of the given string on the
basis of the specified starting position and length.
substring() It is used to fetch the part of the given string on the
basis of the specified index.
slice() It is used to fetch the part of the given string. It allows
us to assign positive as well negative index.
toLowerCase() It converts the given string into lowercase letter.
toLocaleLowerCase() It converts the given string into lowercase
letter on the basis of hosts current locale.
toUpperCase() It converts the given string into uppercase letter.
toLocaleUpperCase() It converts the given string into uppercase
letter on the basis of hosts current locale.
toString() It provides a string representing the particular
object.
valueOf() It provides the primitive value of string object.
String charAt(index) Method
The JavaScript String charAt() method returns
the character at the given index.
<script type=“text/javascript”>
var str="javascript";
document.write(str.charAt(2));
</script>
Output
v
String concat(str)
• The JavaScript String concat(str) method
concatenates or joins two strings.
<script type=“text/javascript”>
var s1="javascript ";
var s2="concat example";
var s3=s1.concat(s2);
document.write(s3);
</script>
Output
javascript concat example
String indexOf(str)
• The JavaScript String indexOf(str) method returns
the index position of the given string.
<script type=“text/javascript”>
var s1="javascript from javatpoint indexof";
var n=s1.indexOf("from");
document.write(n);
</script>
Output
11
String lastIndexOf(str)
• The JavaScript String lastIndexOf(str) method
returns the last index position of the given string.
<script type=“text/javascript”>
var s1="javascript from javascript indexof";
var n=s1.lastIndexOf("java");
document.write(n);
</script>
Output
16
String toLowerCase()/toUpperCase()
• The JavaScript String toLowerCase()/String
toLowerCase() method returns the given
string in lowercase/uppercase letters.
<script type=“text/javascript”>
var s1="JavaScript toLowerCase Example";
var s2=s1.toLowerCase(); //s1.toUpperCase();
document.write(s2);
</script>
String slice(beginIndex, endIndex)
• String slice(beginIndex, endIndex) method returns the
parts of string from given beginIndex to endIndex.
• In slice() method, beginIndex is inclusive and endIndex
is exclusive.
<script type=“text/javascript”>
var s1="abcdefgh";
var s2=s1.slice(2,5);
document.write(s2);
</script>
Output
cde
String trim()
• The JavaScript String trim() method removes
leading and trailing whitespaces from the string.
<script type=“text/javascript”>
var s1=" javascript trim ";
var s2=s1.trim();
document.write(s2);
</script>
Output
javascript trim
toString()
• The JavaScript toString() method returns a string
representing the calling object.
• In other words, this method provides a string
representation of the object and treats same as the
valueof() method.
object.toString()
<script type=“text/javascript”>
var str=“Bsc";
document.writeln(str.toString());
</script>
Output
Bsc
charCodeAt()
• The JavaScript string charCodeAt() method is used to find
out the Unicode value of a character at the specific index in
a string.
• The index number starts from 0 and goes to n-1, where n is
the length of the string.
• It returns NaN if the given index number is either a
negative number or it is greater than or equal to the length
of the string.
<script type=“text/javascript”>
var x="Javascript";
document.writeln(x.charCodeAt(3));
</script>
Output:97
substr()
• The JavaScript string substr() method fetch the part of the
given string and return the new string.
• The number of characters to be fetched depends upon the
length provided with the method.
• This method doesn't make any change in the original string.
<script>
var str="Javascript";
document.writeln(str.substr(0,4));
</script>
Output:
Java
match()
• The JavaScript string match() method is used to
match the string against a regular expression.
• We can use global search modifier with match()
method to get all the match elements otherwise
the method return only first match.
<script>
var str="Javascrit";
document.writeln(str.match(/Java/g));
</script>
parseInt()
• The JavaScript number parseInt() method parses a
string argument and converts it into an integer value.
• With string argument, we can also provide radix
argument to specify the type of numeral system to be
used.
Syntax
Number.parseInt(string, radix)
• string - It represents the string to be parsed.
• radix - It is optional. An integer between 2 and 36 that
represents the numeral system to be used.
Example
<script type=“text/javascript”>
var a="50";
var b="50.25"
var c="String"; // first char. not convert to number, return NaN
var d="50String";
var e="50.25String"
document.writeln(Number.parseInt(a)+"<br>");
document.writeln(Number.parseInt(b)+"<br>");
document.writeln(Number.parseInt(c)+"<br>");
document.writeln(Number.parseInt(d)+"<br>");
document.writeln(Number.parseInt(e));
</script>
Output
50 50 NaN 50 50
parseFloat()
• The JavaScript number parseFloat() method
parses a string argument and converts it into a
floating point number.
• It returns NaN, if the first character of given
value cannot be converted to a number.
Number.parseFloat(string)
• string - It represents the string to be parsed.
Example
<script type=“text/javscript>
var a="50";
var b="50.25"
var c="String";
var d="50String";
var e="50.25String"
document.writeln(Number.parseFloat(a)+"<br>");
document.writeln(Number.parseFloat(b)+"<br>");
document.writeln(Number.parseFloat(c)+"<br>");
document.writeln(Number.parseFloat(d)+"<br>");
document.writeln(Number.parseFloat(e));
</script>
Output
50 50.25 NaN 50 50.25
document.getElementById()
• The document.getElementById() method
returns the element of specified id.
• Use document.getElementById() method to
get value of the input text. But, need to define
id for the input field.
Example
<script type="text/javascript">
function getcube(){
var number=document.getElementById("number").value;
alert(number*number*number);
}
</script>
<form>
Enter No:<input type="text" id="number" name="number"/>
<br/>
<input type="button" value="cube" onclick="getcube()"/>
</form>
Example
<script type="text/javascript">
function getcube(){
var number=document.getElementById("number").
value;
alert(number*number*number);
}
</script>
<form>
Enter No:<input type="text" id="number“ /><br/>
<input type="button" value="cube" onclick="getcube()"/>
</form>
Java script.pptx                                     v
Addition of Two numbers
<html><head>
<script type="text/javascript">
function getadd()
{ var a=parseInt(document.getElementById("number1").value);
var b=parseInt(document.getElementById("number2").value);
alert(a+b); // or document.write(a+b);
}
</script> </head>
<body> <form>
Enter No1:<input type="text" id ="number1"><br>
Enter No2:<input type="text" id ="number2"><br>
<input type="button" value="cube" onclick="getadd()"/>
</form></body></html>
External JavaScript Advantages
• Separating HTML and JavaScript code will help manage the
code base better
• Designers can work along with coders parallel without code
conflicts
• Code as well as HTML is easily readable
• External JavaScript files are cached by browsers and can
speed up page load times
• Many popular JavaScript packages are available as hosted
on content delivery networks (cdn) and you can simply
point to them using the URL in the src, thus avoiding
copying the js file to local folder.

More Related Content

Similar to Java script.pptx v (20)

PPTX
JavaScript_III.pptx
rashmiisrani1
 
PPTX
Introduction to Javascript
ambuj pathak
 
PDF
HSC INFORMATION TECHNOLOGY CHAPTER 3 ADVANCED JAVASCRIPT
AAFREEN SHAIKH
 
PDF
Javascript
20261A05H0SRIKAKULAS
 
PPTX
Java script
Rajkiran Mummadi
 
PDF
Unit 4(it workshop)
Dr.Lokesh Gagnani
 
PDF
Iwt note(module 2)
SANTOSH RATH
 
PPTX
Basics of Javascript
poojanov04
 
PPTX
Final Java-script.pptx
AlkanthiSomesh
 
PPTX
Java script
Jay Patel
 
PPT
Javascript sivasoft
ch samaram
 
PPTX
WTA-MODULE-4.pptx
ChayapathiAR
 
PPTX
Java script
Sukrit Gupta
 
PPTX
Java script basics
Shrivardhan Limbkar
 
PPTX
JAVASCRIPT - LinkedIn
Gino Louie Peña, ITIL®,MOS®
 
PPTX
An introduction to DOM , JAVASCRIPT , JQUERY, AJAX and JSON
Syed Moosa Kaleem
 
PPT
JavaScript Basics with baby steps
Muhammad khurram khan
 
PPTX
JavaScript Fundamentals & JQuery
Jamshid Hashimi
 
PPT
Introduction to javascript.ppt
BArulmozhi
 
JavaScript_III.pptx
rashmiisrani1
 
Introduction to Javascript
ambuj pathak
 
HSC INFORMATION TECHNOLOGY CHAPTER 3 ADVANCED JAVASCRIPT
AAFREEN SHAIKH
 
Java script
Rajkiran Mummadi
 
Unit 4(it workshop)
Dr.Lokesh Gagnani
 
Iwt note(module 2)
SANTOSH RATH
 
Basics of Javascript
poojanov04
 
Final Java-script.pptx
AlkanthiSomesh
 
Java script
Jay Patel
 
Javascript sivasoft
ch samaram
 
WTA-MODULE-4.pptx
ChayapathiAR
 
Java script
Sukrit Gupta
 
Java script basics
Shrivardhan Limbkar
 
JAVASCRIPT - LinkedIn
Gino Louie Peña, ITIL®,MOS®
 
An introduction to DOM , JAVASCRIPT , JQUERY, AJAX and JSON
Syed Moosa Kaleem
 
JavaScript Basics with baby steps
Muhammad khurram khan
 
JavaScript Fundamentals & JQuery
Jamshid Hashimi
 
Introduction to javascript.ppt
BArulmozhi
 

Recently uploaded (20)

PDF
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
PPTX
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
PDF
Is Assignment Help Legal in Australia_.pdf
thomas19williams83
 
PDF
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
PPTX
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
PPTX
Introduction to Biochemistry & Cellular Foundations.pptx
marvinnbustamante1
 
PPTX
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
PPTX
How to Manage Allocation Report for Manufacturing Orders in Odoo 18
Celine George
 
PDF
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
PDF
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
PPTX
infertility, types,causes, impact, and management
Ritu480198
 
PDF
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
PPTX
How to Configure Re-Ordering From Portal in Odoo 18 Website
Celine George
 
PPTX
How to Send Email From Odoo 18 Website - Odoo Slides
Celine George
 
PPTX
Introduction to Indian Writing in English
Trushali Dodiya
 
PDF
Vani - The Voice of Excellence - Jul 2025 issue
Savipriya Raghavendra
 
PPTX
Controller Request and Response in Odoo18
Celine George
 
PPTX
Identifying elements in the story. Arrange the events in the story
geraldineamahido2
 
PPTX
EDUCATIONAL MEDIA/ TEACHING AUDIO VISUAL AIDS
Sonali Gupta
 
PDF
Introduction presentation of the patentbutler tool
MIPLM
 
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
Is Assignment Help Legal in Australia_.pdf
thomas19williams83
 
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
Introduction to Biochemistry & Cellular Foundations.pptx
marvinnbustamante1
 
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
How to Manage Allocation Report for Manufacturing Orders in Odoo 18
Celine George
 
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
infertility, types,causes, impact, and management
Ritu480198
 
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
How to Configure Re-Ordering From Portal in Odoo 18 Website
Celine George
 
How to Send Email From Odoo 18 Website - Odoo Slides
Celine George
 
Introduction to Indian Writing in English
Trushali Dodiya
 
Vani - The Voice of Excellence - Jul 2025 issue
Savipriya Raghavendra
 
Controller Request and Response in Odoo18
Celine George
 
Identifying elements in the story. Arrange the events in the story
geraldineamahido2
 
EDUCATIONAL MEDIA/ TEACHING AUDIO VISUAL AIDS
Sonali Gupta
 
Introduction presentation of the patentbutler tool
MIPLM
 
Ad

Java script.pptx v

  • 1. JavaScript SASIKUMAR M Live as if you were to die tomorrow Learn as if you were to Live forever -Mahatma Gandhi
  • 2. Introduction • JavaScript is used to create client-side dynamic pages. • JavaScript is an object-based scripting language which is lightweight and cross-platform. • JavaScript is not a compiled language, but it is a translated language. • The JavaScript Translator (embedded in the browser) is responsible for translating the JavaScript code for the web browser.
  • 3. Introduction • JavaScript(JS) is a lightweight, interpreted programming language. • It is complimentary to and integrated with Java. • JavaScript is very easy to implement because it is integrated with HTML. • 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 (1990) changed its name to JavaScript by Bredan Eich, 1995 • JavaScript is a case-sensitive language. • JS to program the behavior of web pages
  • 4. • Advantages of JavaScript – Less server interaction − You can validate user input before sending the page off to the server. This saves server traffic, which means less load on your server. – Immediate feedback to the visitors − They don't have to wait for a page reload to see if they have forgotten to enter something. – Increased interactivity − You can create interfaces that react when the user hovers over them with a mouse or activates them via the keyboard. – Richer interfaces − You can use JavaScript to include such items as drag-and-drop components and sliders to give a Rich Interface to your site visitors.
  • 5. • 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.
  • 6. Applications of Javascript • JavaScript is used to create interactive websites. • It is mainly used for: – Client-side validation, – Dynamic drop-down menus, – Displaying date and time, – Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm dialog box and prompt dialog box), – Displaying clocks etc.
  • 7. 3 Places to put JavaScript code • Between the body tag of html • Between the head tag of html • In .js file (external javascript) Example (<body>) <body> <script type="text/javascript"> alert("Hello, Welcome to Javascript"); </script> </body>
  • 8. Between the head tag of html <html> <head> <script type="text/javascript"> function msg() { alert("Hello Students, How R U? "); } </script> </head> <body> <form> <input type="button" value="click" onclick="msg()"/> </form> </body> </html>
  • 9. External JavaScript file • It provides code reusability because single JavaScript file can be used in several html pages message.js function msg() { alert("Hello"); } Externaljs.html <html> <head> <script type="text/javascript" src="message.js"></script> </head> <body> <form> <input type="button" value="click" onclick="msg()"/> </form> </body> </html>
  • 10. Comments • Single-line Comment // It is single line comment • Multi-line Comment /* It is multi line comment. It will not be displayed */
  • 11. Popup Boxes • Alert Box – Warning message • Confirm box – Yes/ No • Prompt box – Reading value from user
  • 12. Alert Box <html> <head> <title> Alert Box </title> </head> <body> <h2>JavaScript Alert</h2> <button onclick="myFunction()">Click</button> <script type=“text/javascript”> function myFunction() {alert("I am an alert box!"); } </script> </body> </html>
  • 13. Confirm box <html> <head><title>Confirm box </title></head> <body> <h2>JavaScript Confirm Box</h2> <button onclick="myFunction()">Click</button> <p id="demo"></p> <script type=“text/javascript”> function myFunction() { var txt; if (confirm("Press a button!")) {txt = "You pressed OK!"; } else { txt = "You pressed Cancel!"; } document.getElementById("demo").innerHTML = txt; } </script> </body> </html>
  • 14. Prompt box <html> <head> <title> Prompt box </title></head> <body> <h2>JavaScript Prompt</h2> <button onclick="myFunction()">Click</button> <p id="demo"></p> <script type=“text/javascript”> function myFunction() { var txt; var person = prompt("Please enter your name:", “BSc"); if (person == null || person == "") { txt = "User cancelled the prompt."; } else { txt = "Hello " + person + "! How are you today?"; } document.getElementById("demo").innerHTML = txt; } </script> </body> </html>
  • 15. JavaScript Variable • A JavaScript variable is simply a name of storage location. • Two types of variables : local variable and global variable. • Rules for declaring a JavaScript variable (also known as identifiers). – Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ ) sign. – After first letter, use digits (0 to 9) – JavaScript variables are case sensitive, for example x and X are different variables. Local variable • A JavaScript local variable is declared inside block or function. It is accessible within the function or block only. <script type=“text/javascript”> function abc(){ var x=10; //local variable } </script>
  • 16. Global variable • Accessible from any function. • A variable i.e. declared outside the function or declared with window object is known as global variable. Example <script type=“text/javascript”> var data=200; //global variable function a(){ document.writeln(data); } function b(){ document.writeln(data); } a(); //calling JavaScript function b(); </script>
  • 17. Java Script Data Types • Data types used to hold different types of values. • Two types of data types – Primitive data type – Non-primitive (reference) data type • JavaScript is a dynamic type language, means no need to specify type of the variable because it is dynamically used by JavaScript engine. • To use var here to specify the data type. It can hold any type of values such as numbers, strings etc. For example: var a=40; //holding number var b=”abcdef"; //holding string
  • 18. Primitive Datatype Data Type Description String represents sequence of characters e.g. "hello“ Number represents numeric values e.g. 100 Boolean represents boolean value either false or true Undefined represents undefined value Null represents null i.e. no value at all
  • 19. JavaScript non-primitive data types Data Type Description Object represents instance through which we can access members Array represents group of similar values RegExp represents regular expression
  • 20. Java Script Operators • Arithmetic Operators • Comparison (Relational) Operators • Bitwise Operators • Logical Operators • Assignment Operators • Special Operators
  • 21. Arithmetic operator Operator Description Example + Addition 10+20 = 30 - Subtraction 20-10 = 10 * Multiplication 10*20 = 200 / Division 20/10 = 2 % Modulus (Remainder) 20%10 = 0 ++ Increment var a=10; a++; Now a = 11 -- Decrement var a=10; a--; Now a = 9
  • 22. JavaScript Comparison Operators Operator Description Example == Is equal to 10==20 = false === Identical (equal and of same type) 10==20 = false != Not equal to 10!=20 = true !== Not Identical20!==20 = false > Greater than 20>10 = true >= Greater than or equal to20>=10 = true < Less than 20<10 = false <= Less than or equal to 20<=10 = false
  • 23. JavaScript Bitwise Operators Operator Description Example & Bitwise AND (10==20 & 20==33) = false | Bitwise OR (10==20 | 20==33) = false ^ Bitwise XOR (10==20 ^ 20==33) = false ~ Bitwise NOT (~10) = -10 << Bitwise Left Shift (10<<2) = 8 >> Bitwise Right Shift (negative number) (10>>2) = 2 >>> Bitwise Right Shift with Zero (positive number) (10>>>2) = 2
  • 24. JavaScript Logical Operators Operator Description Example && Logical AND (10==20 && 20==33) = false || Logical OR (10==20 || 20==33) = false ! Logical Not !(10==20) = true
  • 25. JavaScript Assignment Operators Operator Description Example = Assign 10+10 = 20 += Add and assign var a=10; a+=20; Now a 30 -= Subtract and assign var a=20; a-=10; Now a 10 *= Multiply and assign var a=5; a*=20; Now a 100 /= Divide and assign var a=10; a/=2; Now a = 5 %= Modulus and assign var a=10; a%=2; Now a = 0
  • 26. JavaScript Special Operators Operator Description (?:) 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 New creates an instance (object) type of checks the type of object. Void it discards the expression's return value. Yield checks what is returned in a generator by the generator's iterator.
  • 27. Conditional Statements • Selection – If Statement – If else statement – if else if statement • Loop – While – Do-while – For – For-in • Switch – Multiway branch
  • 28. IF Statement • It evaluates the content only if expression is true. • The signature of JavaScript if statement is given below. if(expression){ //content to be evaluated } Example <script type=“text/javascript”> var a=20; if(a>10){ document.write("value of a is greater than 10"); } </script>
  • 29. If...else Statement • It evaluates the content whether condition is true of false. • The syntax of JavaScript if-else statement is given below. if(expression){ //content to be evaluated if condition is true } else{ //content to be evaluated if condition is false }
  • 30. Example <script type=“text/javascript”> var a=20; if(a%2==0){ document.write("a is even number"); } else{ document.write("a is odd number"); } </script>
  • 31. JavaScript If...else if statement • It evaluates the content only if expression is true from several expressions. • The signature of JavaScript if else if statement is given below. if(expression1){ //content to be evaluated if expression1 is true } else if(expression2){ //content to be evaluated if expression2 is true } else if(expression3){ //content to be evaluated if expression3 is true } else{ //content to be evaluated if no expression is true }
  • 32. Example <script type=“text/javascript”> var a=20; if(a==10){ document.write("a is equal to 10"); } else if(a==15){ document.write("a is equal to 15"); } else if(a==20){ document.write("a is equal to 20"); } else{ document.write("a is not equal to 10, 15 or 20"); } </script>
  • 33. switch statement • Used to execute one code from multiple expressions. • It is just like if..else..if statement that discussed in previous slide. • But it is convenient than if..else..if • The signature of JavaScript switch statement is given below.
  • 34. Syntax switch(expression){ case value1: code to be executed; break; case value2: code to be executed; break; ...... default: code to be executed if above values are not matched; }
  • 35. Example <script type=“text/javascript”> var grade='B'; var result; switch(grade){ case 'A': result="A Grade"; break; case 'B': result="B Grade"; break; case 'C': result="C Grade"; break; default: result="No Grade"; } } document.write(result); </script>
  • 36. while loop • Iterates the elements for the infinite number of times. • It should be used if number of iteration is not known. • The syntax of while loop is given below. while (condition) { code to be executed }
  • 37. Example <script type=“text/javascript”> var i=11; while (i<=15) { document.write(i + "<br/>"); i++; } </script>
  • 38. do while loop • Iterates the elements for the infinite number of times like while loop. • But, code is executed at least once whether condition is true or false. • The syntax of do while loop is given below. do{ code to be executed }while (condition);
  • 40. For loop • Iterates the elements for the fixed number of times. • It should be used if number of iteration is known. The syntax of for loop is given below. for (initialization; condition; increment) { code to be executed }
  • 41. Example <script type=“text/javascript”> for (i=1; i<=5; i++) { document.write(i + "<br/>") } </script>
  • 42. for in loop • To iterate the properties of an object.
  • 43. Function • JavaScript functions are used to perform operations. • Call JavaScript function many times to reuse the code. • Advantage of JavaScript function – Code reusability: Call a function several times so it save coding. – Less coding: It makes our program compact. No need to write many lines of code each time to perform a common task. Syntax function functionName([arg1, arg2, ...argN]) { //code to be executed }
  • 44. Example <script type=“text/javascript”> function msg(){ alert("hello! this is message"); } </script> <input type="button" onclick="msg()" value="call function"/>
  • 45. Function with Argument <script type=“text/javascript”> function getcube(number){ alert(number*number*number); } </script> <form> <input type="button" value="click" onclick="getcube(4)"/> </form>
  • 46. Function with return value <script type=“text/javascript”> function getInfo(){ return "hello students! How r u?"; } </script> <form> <input type="button" value="click" onclick="getinfo()"/> </form>
  • 47. Array • JavaScript Array is an object that represents a collection of similar type of elements. • 3 ways to construct array in JavaScript – By array literal – By creating instance of Array directly (using new keyword) – By using an Array constructor (using new keyword)
  • 48. • JavaScript array literal – var arrayname=[value1,value2.....valueN]; Example <script type=“text/javascript”> var stu=[“abc",“def",“ijk"]; for (i=0;i<stu.length;i++){ document.write(stu[i] + "<br/>"); } </script>
  • 49. • JavaScript Array directly (new keyword) var arrayname=new Array(); <script type=“text/javascript”> var i; var stu = new Array(); stu[0] = “abc"; stu[1] = “cde"; stu[2] = “fgh"; for (i=0;i<stu.length;i++){ document.write(stu[i] + "<br>"); } </script>
  • 50. • JavaScript array constructor (new keyword) <script type=“text/javascript”> var stu=new Array(“abc",“cde",“fgh"); for (i=0;i<stu.length;i++){ document.write(stu[i] + "<br>"); } </script>
  • 51. JavaScript Array Methods Methods Description concat() It returns a new array object that contains two or more merged arrays. copywithin() It copies the part of the given array with its own elements and returns the modified array. every() It determines whether all the elements of an array are satisfying the provided function conditions. fill() It fills elements into an array with static values. filter() It returns the new array containing the elements that pass the provided function conditions. find() It returns the value of the first element in the given array that satisfies the specified condition. findIndex() It returns the index value of the first element in the given array that satisfies the specified condition. forEach() It invokes the provided function once for each element of an array. includes() It checks whether the given array contains the specified element. indexOf() It searches the specified element in the given array and returns the index of the first match.
  • 52. join() It joins the elements of an array as a string. lastIndexOf() It searches the specified element in the given array and returns the index of the last match. map() It calls the specified function for every array element and returns the new array pop() It removes and returns the last element of an array. push() It adds one or more elements to the end of an array. reverse() It reverses the elements of given array. shift() It removes and returns the first element of an array. slice() It returns a new array containing the copy of the part of the given array. sort() It returns the element of the given array in a sorted order. splice() It add/remove elements to/from the given array. unshift() It adds one or more elements in the beginning of the given array.
  • 53. Concat example <script type=“text/javascript”> var arr1=["C","C++","Python"]; var arr2=["Java","JavaScript","Android"]; var result=arr1.concat(arr2); document.writeln(result); </script> Output C,C++,Python,Java,JavaScript,Android
  • 54. Array sort() method • The JavaScript array sort() method is used to arrange the array elements in some order. • By default, sort() method follows the ascending order. Example <script type=“text/javascript”> var arr=["AngularJS","Node.js","JQuery","Bootstrap"] var result=arr.sort(); document.writeln(result); </script> Output AngularJS,Bootstrap,JQuery,Node.js
  • 55. slice() method • Array slice() method extracts the part of the given array and returns it. • This method doesn't change the original array. array.slice(start,end) • start - It is optional. It represents the index from where the method starts to extract the elements. • end - It is optional. It represents the index at where the method stops extracting elements. <script type=“text/javascript”> var arr=["AngularJS","Node.js","JQuery","Bootstrap"] var result=arr.slice(1,2); document.writeln(result); </script> Output: Node.js
  • 56. indexOf() method • Array indexOf() method is used to search the position of a particular element in a given array. • This method is case-sensitive. • The index position of first element in an array is always start with zero. If an element is not present in an array, it returns -1. array.indexOf(element,index) • element - It represent the element to be searched. • index - It represent the index position from where search starts. It is optional.
  • 57. Example <script type=“text/javascript”> var arr=["C","C++","Python","C++","Java"]; var result= arr.indexOf("C++"); document.writeln(result); </script> Output 1
  • 58. join() • Array join() method combines all the elements of an array into a string and return a new string. • We can use any type of separators to separate given array elements. array.join(separator) • Separator() - It is optional. It represent the separator used between array elements.
  • 59. Example <script type=“text/javascript”> var arr=["AngularJs","Node.js","JQuery"] var result=arr.join('-') document.write(result); </script> Output AngularJs-Node.js-JQuery
  • 60. reverse() • Array reverse() method changes the sequence of elements of the given array and returns the reverse sequence. array.reverse() Example <script type=“text/javascript”> var arr=["AngulaJS","Node.js","JQuery"]; var rev=arr.reverse(); document.writeln(rev); </script> Output JQuery,Node.js,AngulaJS
  • 61. every() • The JavaScript array every() method checks whether all the given elements in an array are satisfying the provided condition. • It returns true when each given array element satisfying the condition otherwise false. <script type=“text/javascript”> var marks=[50,40,45,37,20]; function check(value) { return value>30; //return false, as marks[4]=20 } document.writeln(marks.every(check)); </script>
  • 62. copyWithin() • The JavaScript array copyWithin() method copies the part of the given array with its own elements and returns the modified array. • This method doesn't change the length of the modified array. <script type=“text/javascript”> var arr=["AngularJS","Node.js","JQuery","Bootstrap"] // place at 0th position, the element between 1st and 2nd position. var result=arr.copyWithin(0,1,2); document.writeln(result); </script> Output:Node.js,Node.js,,Jquery,Bootstrap
  • 63. Filter() • The JavaScript array filter() method filter and extract the element of an array that satisfying the provided condition. • It doesn't change the original array. <script type=“text/javascript”> var marks=[50,40,45,37,20]; function check(value) { return value>30; } document.writeln(marks.filter(check)); </script> Output: [50,40,45,37]
  • 64. fill() • The JavaScript array fill() method fills the elements of the given array with the specified static values. This method modifies the original array. • It returns undefined, if no element satisfies the condition. <script type=“text/javascript”> var arr=["AngularJS","Node.js","JQuery"]; var result=arr.fill("Bootstrap"); document.writeln(arr); </script> Output: Bootstrap, Bootstrap, Bootstrap
  • 65. find() • The JavaScript array find() method returns the first element of the given array that satisfies the provided function condition. <script type=“text/javascript”> var arr=[5,22,19,25,34]; var result=arr.find(x=>x>20); document.writeln(result) </script> output:22
  • 66. forEach() • The JavaScript array forEach() method is used to invoke the specified function once for each array element. <script type=“text/javascript”> var sum = 0; var arr = [10,18,12,20]; arr.forEach(function myFunction(element) { sum= sum+element; document.writeln(sum); }); </script>
  • 67. string • String is an object that represents a sequence of characters. • There are 2 ways to create string in JavaScript – By string literal – By string object (using new keyword) By string literal var stringname="string value"; <script type=“text/javascript”> var str=“Hi Welcome!"; document.write(str); </script> OUTPUT Hi Welcome!
  • 68. By string object (using new keyword) • var stringname=new String("string literal"); <script type=“text/javascript”> var stringname=new String ("hello javascript string"); document.write(stringname); </script> Output: hello javascript string
  • 69. String Methods Methods Description charAt() It provides the char value present at the specified index. charCodeAt() It provides the Unicode value of a character present at the specified index. concat() It provides a combination of two or more strings. indexOf() It provides the position of a char value present in the given string. lastIndexOf() It provides the position of a char value present in the given string by searching a character from the last position. search() It searches a specified regular expression in a given string and returns its position if a match occurs. match() It searches a specified regular expression in a given string and returns that regular expression if a match occurs. replace() It replaces a given string with the specified replacement.
  • 70. substr() It is used to fetch the part of the given string on the basis of the specified starting position and length. substring() It is used to fetch the part of the given string on the basis of the specified index. slice() It is used to fetch the part of the given string. It allows us to assign positive as well negative index. toLowerCase() It converts the given string into lowercase letter. toLocaleLowerCase() It converts the given string into lowercase letter on the basis of hosts current locale. toUpperCase() It converts the given string into uppercase letter. toLocaleUpperCase() It converts the given string into uppercase letter on the basis of hosts current locale. toString() It provides a string representing the particular object. valueOf() It provides the primitive value of string object.
  • 71. String charAt(index) Method The JavaScript String charAt() method returns the character at the given index. <script type=“text/javascript”> var str="javascript"; document.write(str.charAt(2)); </script> Output v
  • 72. String concat(str) • The JavaScript String concat(str) method concatenates or joins two strings. <script type=“text/javascript”> var s1="javascript "; var s2="concat example"; var s3=s1.concat(s2); document.write(s3); </script> Output javascript concat example
  • 73. String indexOf(str) • The JavaScript String indexOf(str) method returns the index position of the given string. <script type=“text/javascript”> var s1="javascript from javatpoint indexof"; var n=s1.indexOf("from"); document.write(n); </script> Output 11
  • 74. String lastIndexOf(str) • The JavaScript String lastIndexOf(str) method returns the last index position of the given string. <script type=“text/javascript”> var s1="javascript from javascript indexof"; var n=s1.lastIndexOf("java"); document.write(n); </script> Output 16
  • 75. String toLowerCase()/toUpperCase() • The JavaScript String toLowerCase()/String toLowerCase() method returns the given string in lowercase/uppercase letters. <script type=“text/javascript”> var s1="JavaScript toLowerCase Example"; var s2=s1.toLowerCase(); //s1.toUpperCase(); document.write(s2); </script>
  • 76. String slice(beginIndex, endIndex) • String slice(beginIndex, endIndex) method returns the parts of string from given beginIndex to endIndex. • In slice() method, beginIndex is inclusive and endIndex is exclusive. <script type=“text/javascript”> var s1="abcdefgh"; var s2=s1.slice(2,5); document.write(s2); </script> Output cde
  • 77. String trim() • The JavaScript String trim() method removes leading and trailing whitespaces from the string. <script type=“text/javascript”> var s1=" javascript trim "; var s2=s1.trim(); document.write(s2); </script> Output javascript trim
  • 78. toString() • The JavaScript toString() method returns a string representing the calling object. • In other words, this method provides a string representation of the object and treats same as the valueof() method. object.toString() <script type=“text/javascript”> var str=“Bsc"; document.writeln(str.toString()); </script> Output Bsc
  • 79. charCodeAt() • The JavaScript string charCodeAt() method is used to find out the Unicode value of a character at the specific index in a string. • The index number starts from 0 and goes to n-1, where n is the length of the string. • It returns NaN if the given index number is either a negative number or it is greater than or equal to the length of the string. <script type=“text/javascript”> var x="Javascript"; document.writeln(x.charCodeAt(3)); </script> Output:97
  • 80. substr() • The JavaScript string substr() method fetch the part of the given string and return the new string. • The number of characters to be fetched depends upon the length provided with the method. • This method doesn't make any change in the original string. <script> var str="Javascript"; document.writeln(str.substr(0,4)); </script> Output: Java
  • 81. match() • The JavaScript string match() method is used to match the string against a regular expression. • We can use global search modifier with match() method to get all the match elements otherwise the method return only first match. <script> var str="Javascrit"; document.writeln(str.match(/Java/g)); </script>
  • 82. parseInt() • The JavaScript number parseInt() method parses a string argument and converts it into an integer value. • With string argument, we can also provide radix argument to specify the type of numeral system to be used. Syntax Number.parseInt(string, radix) • string - It represents the string to be parsed. • radix - It is optional. An integer between 2 and 36 that represents the numeral system to be used.
  • 83. Example <script type=“text/javascript”> var a="50"; var b="50.25" var c="String"; // first char. not convert to number, return NaN var d="50String"; var e="50.25String" document.writeln(Number.parseInt(a)+"<br>"); document.writeln(Number.parseInt(b)+"<br>"); document.writeln(Number.parseInt(c)+"<br>"); document.writeln(Number.parseInt(d)+"<br>"); document.writeln(Number.parseInt(e)); </script> Output 50 50 NaN 50 50
  • 84. parseFloat() • The JavaScript number parseFloat() method parses a string argument and converts it into a floating point number. • It returns NaN, if the first character of given value cannot be converted to a number. Number.parseFloat(string) • string - It represents the string to be parsed.
  • 85. Example <script type=“text/javscript> var a="50"; var b="50.25" var c="String"; var d="50String"; var e="50.25String" document.writeln(Number.parseFloat(a)+"<br>"); document.writeln(Number.parseFloat(b)+"<br>"); document.writeln(Number.parseFloat(c)+"<br>"); document.writeln(Number.parseFloat(d)+"<br>"); document.writeln(Number.parseFloat(e)); </script> Output 50 50.25 NaN 50 50.25
  • 86. document.getElementById() • The document.getElementById() method returns the element of specified id. • Use document.getElementById() method to get value of the input text. But, need to define id for the input field.
  • 87. Example <script type="text/javascript"> function getcube(){ var number=document.getElementById("number").value; alert(number*number*number); } </script> <form> Enter No:<input type="text" id="number" name="number"/> <br/> <input type="button" value="cube" onclick="getcube()"/> </form>
  • 88. Example <script type="text/javascript"> function getcube(){ var number=document.getElementById("number"). value; alert(number*number*number); } </script> <form> Enter No:<input type="text" id="number“ /><br/> <input type="button" value="cube" onclick="getcube()"/> </form>
  • 90. Addition of Two numbers <html><head> <script type="text/javascript"> function getadd() { var a=parseInt(document.getElementById("number1").value); var b=parseInt(document.getElementById("number2").value); alert(a+b); // or document.write(a+b); } </script> </head> <body> <form> Enter No1:<input type="text" id ="number1"><br> Enter No2:<input type="text" id ="number2"><br> <input type="button" value="cube" onclick="getadd()"/> </form></body></html>
  • 91. External JavaScript Advantages • Separating HTML and JavaScript code will help manage the code base better • Designers can work along with coders parallel without code conflicts • Code as well as HTML is easily readable • External JavaScript files are cached by browsers and can speed up page load times • Many popular JavaScript packages are available as hosted on content delivery networks (cdn) and you can simply point to them using the URL in the src, thus avoiding copying the js file to local folder.