SlideShare uma empresa Scribd logo
1 de 75
Java Script Basic
BCA -302
2
What is JavaScript?
 JavaScript was initially created to “make web pages alive”.
 The programs in this language are called scripts.
 They can be written right in a web page’s HTML and run automatically as the page
loads.
 Scripts are provided and executed as plain text.
 They don’t need special preparation or compilation to run.
 JavaScript is a lightweight, interpreted programming language.
 It is designed for creating network-centric applications.
 It is complimentary to and integrated with Java.
 JavaScript is very easy to implement because it is integrated with HTML. It is open
and cross-platform.
3
Why is it called ‘JavaScript’?
When JavaScript was created, it initially had another name: “LiveScript”.
 But Java was very popular at that time, so it was decided that positioning a new
language as a “younger brother” of Java would help.
But as it evolved, JavaScript became a fully independent language with its own
specification called ECMAScript, and now it has no relation to Java at all.
Today, JavaScript can execute not only in the browser, but also on the server, or
actually on any device that has a special program called the JavaScript engine.
The browser has an embedded engine sometimes called a “JavaScript virtual
machine”.
4
Advantages of Java Script
 Javascript is the most popular programming language in the world and that makes it a
programmer’s great choice. Once you learnt Javascript, it helps to develop great front-end as well
as back-end softwares using different Javascript based frameworks like jQuery, Node.JS etc.
 Javascript is everywhere, it comes installed on every modern web browser and so to learn
Javascript you really do not need any special environment setup. For example Chrome, Mozilla
Firefox , Safari and every browser you know as of today, supports Javascript.
 Javascript helps to create really beautiful and crazy fast websites. One can develop own website
with a console like look and feel and give users the best Graphical User Experience.
 JavaScript usage has now extended to mobile app development, desktop app development, and
game development. This opens many opportunities for you as Javascript Programmer.
 Due to high demand, there is tons of job growth and high pay for those who know JavaScript.
 There are many useful Javascript frameworks and libraries available: Angular, React ,jQuery,
Vue.js, Ext.js, Ember.js, Meteor, Mithril, Node.js, Polymer, Aurelia, Backbone.js
5
Applications of JavaScript
 Client side validation - This is really important to verify any user input before submitting it to the
server and Javascript plays an important role in validting those inputs at front-end itself.
 Manipulating HTML Pages - Javascript helps in manipulating HTML page on the fly. This helps
in adding and deleting any HTML tag very easily using javascript and modify your HTML to
change its look and feel based on different devices and requirements.
 User Notifications - You can use Javascript to raise dynamic pop-ups on the webpages to give
different types of notifications to your website visitors.
 Back-end Data Loading - Javascript provides Ajax library which helps in loading back-end data
while you are doing some other processing. This really gives an amazing experience to your
website visitors.
 Presentations - JavaScript also provides the facility of creating presentations which gives
website look and feel. JavaScript provides RevealJS and BespokeJS libraries to build a web-
based slide presentations.
 Server Applications - Node JS is built on Chrome's Javascript runtime for building fast and
scalable network applications. This is an event based library which helps in developing very
sophisticated server applications including Web Servers.
6
Limitations of JavaScript
 Client-side JavaScript does not allow the reading or writing of files. This has been kept for security
reason.
 JavaScript cannot be used for networking applications because there is no such support
available.
 JavaScript doesn't have any multi-threading or multiprocessor capabilities
7
What makes JavaScript Unique?
There are at least three great things about JavaScript:
1. Full integration with HTML/CSS.
2. Simple things are done simply.
3. Support by all major browsers and enabled by default.
JavaScript is the only browser technology that combines these three things.
That’s what makes JavaScript unique. That’s why it’s the most widespread tool for
creating browser interfaces. That said, JavaScript also allows to create servers, mobile
applications, etc.
8
JavaScript Syntax
JavaScript can be implemented using JavaScript statements that are placed within the <script>...
</script> HTML tags in a web page
The <script> tag alerts the browser program to start interpreting all the text between these tags as a
script
<script language = "javascript" type = "text/javascript">
JavaScript code
</script>
The script tag takes two important attributes −
Language − This attribute specifies what scripting language you are using. Typically, its value will be
javascript. Although recent versions of HTML (and XHTML, its successor) have phased out the use of
this attribute.
Type − This attribute is what is now recommended to indicate the scripting language in use and its
value should be set to "text/javascript".
9
Comments in JavaScript
JavaScript supports both C-style and C++-style comments, Thus −
 Any text between a // and the end of a line is treated as a comment and is ignored by JavaScript.
 Any text between the characters /* and */ is treated as a comment. This may span multiple lines.
 JavaScript also recognizes the HTML comment opening sequence <!--. JavaScript treats this as a
single-line comment, just as it does the // comment.
 The HTML comment closing sequence --> is not recognized by JavaScript so it should be written
as //-->.
<script language = "javascript" type = "text/javascript">
<!--
// This is a comment. It is similar to comments in C++
/*
* This is a multi-line comment in JavaScript
* It is very similar to comments in C Programming
*/
//-->
</script>
10
JavaScript - Placement in HTML File
There is a flexibility given to include JavaScript code anywhere in an HTML document. However the
most preferred ways to include JavaScript in an HTML file are as follows −
 Script in <head>...</head> section.
 Script in <body>...</body> section.
 Script in <body>...</body> and <head>...</head> sections.
 Script in an external file and then include in <head>...</head> section
11
JavaScript in <head>----</head> section
<html>
<head>
<script type = "text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<input type = "button" onclick = "sayHello()" value = "Say Hello" />
</body>
</html>
12
JavaScript in <body>…</body> section
<html>
<head>
</head>
<body>
<script type = "text/javascript">
<!--
document.write("Hello World")
//-->
</script>
<p>This is web page body </p>
</body>
</html>
13
JavaScript in <body> & <head> section
<html>
<head>
<script type = "text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<script type = "text/javascript">
<!--
document.write("Hello World")
//-->
</script>
<input type = "button" onclick = "sayHello()" value = "Say Hello" />
</body>
</html>
14
JavaScript in External file
<html>
<head>
<script type = "text/javascript" src = "filename.js" ></script>
</head>
<body>
.......
</body>
</html>
The script tag provides a mechanism to allow to store JavaScript in an external file and then include
it into HTML files.
To use JavaScript from an external file source, it is needed to write all JavaScript source code in a
simple text file with the extension ".js" and then include that file as shown below.
15
JavaScript- variable
A JavaScript variable is simply a name of storage location. Variables are used to store information.
A variable's value can change during the script. JavaScript variables are case sensitive so watch
upper case and lower case letters when referring to a variable. They also must start with letter or
underscore. There are two types of variables in JavaScript : local variable and global variable.
There are some rules while 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 we can use digits (0 to 9), for example value1.
 JavaScript variables are case sensitive, for example x and X are different variables.
 Declare a variable in JavaScript variable like this:
var name;. This means, create variable name.
Var is term used to declare a java and JavaScript variables.
Assign a value to the variable like this:
name="G. Danyeer";. This simply assigns the value G. Danyeer to the variable name.
One can declare and assign a value in single statement as follows:
var name = "G. Danyeer";
16
JavaScript- local variable
A JavaScript local variable is declared inside block or function. It is accessible within the function or
block only. For example:
<script>
function abc(){
var x=10;//local variable
}
</script>
Or,
<script>
If(10<13){
var y=20;//JavaScript local variable
}
</script>
17
JavaScript- global variable
A JavaScript global variable is accessible from any function. A variable i.e. declared outside the
function or declared with window object is known as global variable. For example:
<script>
var data=200;//gloabal variable
function a(){
document.writeln(data);
}
function b(){
document.writeln(data);
}
a();//calling JavaScript function
b();
</script>
18
JavaScript- data types
JavaScript provides different data types to hold different types of values. There are two types of data
types in JavaScript.
 Primitive data type
 Non-primitive (reference) data type
JavaScript is a dynamic type language, means there is no need to specify type of the variable
because it is dynamically used by JavaScript engine.
One need 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="Rahul";//holding string
19
JavaScript- Primitive Data Types
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
20
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
21
Empty Values
An empty value has nothing to do with undefined. An empty string has both a legal value and a
type.
var car = ""; // The value is "", the typeof is "string"
Undefined
In JavaScript, a variable without a value, has the value undefined. The type is also undefined.
var car; // Value is undefined, type is undefined
Null
In JavaScript null is "nothing". It is supposed to be something that doesn't exist. Unfortunately,
in JavaScript, the data type of null is an object.
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
person = null; // Now value is null, but type is still an object
JavaScript- Data Types
22
Javascript- Reserved Words
abstract else instanceof switch
boolean enum int synchronized
break export interface this
byte extends long throw
case false native throws
catch final new transient
char finally null true
class float package try
const for private typeof
continue function protected var
debugger goto public void
default if return volatile
delete implements short while
do import static with
double in super
23
JavaScript- Operators
JavaScript operators are symbols that are used to perform operations on operands.
There are following types of operators in JavaScript.
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
6. Special Operators
24
Javascript- Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations on the operands. The following
operators are known as JavaScript arithmetic operators.
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
25
JavaScript- Comparison Operators
The JavaScript comparison operator compares the two operands. The comparison operators are as
follows:
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 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
26
JavaScript- Bitwise Operators
The bitwise operators perform bitwise operations on operands. The bitwise operators are as follows:
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) = 40
>> Bitwise Right Shift (10>>2) = 2
>>> Bitwise Right Shift with Zero (10>>>2) = 2
27
JavaScript- Bitwise Operators
The bitwise operators perform bitwise operations on operands. The bitwise operators are as follows:
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) = 40
>> Bitwise Right Shift (10>>2) = 2
>>> Bitwise Right Shift with Zero (10>>>2) = 2
28
JavaScript- Logical Operators
The following operators are known as 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
29
JavaScript- Assignment Operators
The following operators are known as 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=10; a*=20; Now a = 200
/= Divide and assign var a=10; a/=2; Now a = 5
%= Modulus and assign var a=10; a%=2; Now a = 0
30
JavaScript- Special Operators
The following operators are known as 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)
typeof 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.
31
JavaScript- typeof Operators
The typeof operator is a unary operator that is placed before its single operand, which can be of any
type. Its value is a string indicating the data type of the operand.
The typeof operator evaluates to "number", "string", or "boolean" if its operand is a number, string, or
boolean value and returns true or false based on the evaluation.
Type String Returned by typeof
Number "number"
String "string"
Boolean "boolean"
Object "object"
Function "function"
Undefined "undefined"
Null "object"
32
Example of typeof Operators
<html>
<body>
<script type = "text/javascript">
<!--
var a = 10;
var b = "String";
var linebreak = "<br />";
result = (typeof b == "string" ? "B is String" : "B is Numeric");
document.write("Result => ");
document.write(result);
document.write(linebreak);
result = (typeof a == "string" ? "A is String" : "A is Numeric");
document.write("Result => ");
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>
33
Typecasting
 Typecasting or coercion in simple term means to change the data type of a value
to another data type like for example, integer to a string or a string to a boolean etc.
 There are two types of coercion, implicit and explicit.
 Implicit coercion is when there is automatic conversion of data type, where as When a
developer expresses the intention to convert between types by writing the appropriate
code, it’s called explicit type coercion (or type casting)
 JavaScript only supports three type of conversion
1. to string
2. to boolean
3. to number
 Number() converts to a Number, String() converts to a String, Boolean() converts to a
Boolean.
34
String Typecasting
 We can explicitly convert values to a string using the String() method .
 Also JavaScript does a implicit string coercion when used with the+ operator.
The most trivial example would be concatenation.
val = 5
String(val) //explicit coercion
'10' + val //105 not 15 and o/p is a String, implicit coercion
 All other primitive values are converted to string naturally
String(true) // 'true'
String(false) // 'false'
String(0) // '0'
String(-0.99) // '-0.99'
String(null) // "null"
String(undefined) // "undefined"
35
Boolean Typecasting
 To explicitly convert values to boolean we use the Boolean() method. Implicit
conversion is done happens in logical context i.e if else statements and by
logical operators ( || && !) .
 The Boolean() type cast returns true when the value is a string with at least one
character, a number other than 0, or an object ; it returns false when the value is
an empty string, the number 0, undefined , or null .
Boolean(0) //false
Boolean(null) //false
Boolean(undefined) //false
Boolean('') //false
Boolean('hi') //true
Boolean(-1.2) //true
Boolean(new Date()) //true
 implicit
Boolean(2 || 'hello') true
Boolean(0 && new Date()) false
if(2) { ... }  true
Boolean(0 == '0')  true
Boolean(0 === '0')  false
36
Numeric Typecasting
 To explicitly convert a value to a number we use the Number() method.
 The number method converts to both integer and float.
 Number() method calls two different methods, parseInt() and parseFloat() implicitly
depending on the value.
Number("5.6.7") //NaN
parseInt("5.5.5") //5
parseFloat("5.5.5") //5.5
 Comparison, bitwise and arithmetic operator uses implicit number conversion except
for the arithmetic operator +, if there is a string, then this operator uses String()method
instead for Number()
37
JavaScript if…else statement
 JavaScript supports conditional statements
which are used to perform different actions
based on different conditions.
 JavaScript supports the following forms
of if..else statement −
I. if statement
II. if...else statement
III. if...else if... statement.
38
JavaScript if…else statement
 if statement
The if statement is the fundamental control
statement that allows JavaScript to make decisions
and execute statements conditionally.
Syntax:
if (expression) {
Statement(s) to be executed if expression is true
}
 Here a JavaScript expression is evaluated. If
the resulting value is true, the given
statement(s) are executed. If the expression is
false, then no statement would be not
executed. Most of the times, you will use
comparison operators while making decisions.
<html>
<body>
<script type = "text/javascript">
<!--
var age = 20;
if( age > 18 ) {
document.write("<b>Qualifies for
driving</b>");
}
//-->
</script>
<p>Set the variable to different value and then
try...</p>
</body>
</html>
39
JavaScript if…else statement
 If…else statement
The 'if...else' statement is the next form of control
statement that allows JavaScript to execute
statements in a more controlled way.
Syntax:
if (expression) {
Statement(s) to be executed if expression is true
} else {
Statement(s) to be executed if expression is false
}
 Here JavaScript expression is evaluated. If the
resulting value is true, the given statement(s)
in the ‘if’ block, are executed. If the expression
is false, then the given statement(s) in the else
block are executed.
<html>
<body>
<script type = "text/javascript">
<!--
var age = 20;
if( age > 18 ) {
document.write("<b>Qualifies for
driving</b>");
} else {
document.write("<b>Does not qualify for
driving</b>");
} //-->
</script>
<p>Set the variable to different value and then
try...</p>
</body>
</html>
40
JavaScript if…else statement
 If…else if... statement
The if...else if... statement is an advanced form
of if…else that allows JavaScript to make a correct
decision out of several conditions.
Syntax:
if (expression 1) {
Statement(s) to be executed if expression 1 is true
} else if (expression 2) {
Statement(s) to be executed if expression 2 is true
} else if (expression 3) {
Statement(s) to be executed if expression 3 is true
} else {
Statement(s) to be executed if no expression is
true
}
 It is just a series of if statements, where each if is
a part of the else clause of the previous
statement. Statement(s) are executed based on
the true condition, if none of the conditions is true,
then the else block is executed
<html>
<body>
<script type = "text/javascript">
<!--
var book = "maths";
if( book == "history" ) {
document.write("<b>History Book</b>");
} else if( book == "maths" ) {
document.write("<b>Maths Book</b>");
} else if( book == "economics" ) {
document.write("<b>Economics Book</b>");
} else {
document.write("<b>Unknown Book</b>");
}//-->
</script>
<p>Set the variable to different value and then
try...</p>
</body>
</html>
41
JavaScript switch statement
 The JavaScript switch statement is
used to execute one code from multiple
expressions. It is just like else if
statement that we have learned in
previous page. But it is convenient
than if..else..if because it can be used
with numbers, characters etc.
 The objective of a switch statement is to
give an expression to evaluate and
several different statements to execute
based on the value of the expression.
The interpreter checks each case against
the value of the expression until a match
is found. If nothing matches,
a default condition will be used.
42
JavaScript switch statement
switch (expression) {
case condition 1: statement(s)
break;
case condition 2: statement(s)
break;
...
case condition n: statement(s)
break;
default: statement(s)
}
The break statements indicate the end of a
particular case. If they were omitted, the
interpreter would continue executing each
statement in each of the following cases.
<html>
<body>
<script type = "text/javascript">
<!--
var grade = 'A';
document.write("Entering switch block<br />");
switch (grade) {
case 'A': document.write("Good job<br />");
break;
case 'B': document.write("Pretty good<br />");
break;
case 'C': document.write("Passed<br />");
break;
case 'D': document.write("Not so good<br />");
break;
case 'F': document.write("Failed<br />");
break;
default: document.write("Unknown grade<br />")
}
document.write("Exiting switch block");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
43
JavaScript loop statement
The JavaScript loops are used to iterate the piece of code using for, while, do while or
for-in loops. It makes the code compact. It is mostly used in array.
There are four types of loops in JavaScript.
1. while loop
2. do-while loop
3. for loop
4. for-in loop
44
JavaScript while loop statement
The purpose of a while loop is to execute a statement or code block repeatedly as long as an expression is true. Once
the expression becomes false, the loop terminates
Syntax:
while (expression) {
Statement(s) to be executed if expression is true
}
<html>
<body>
<script type = "text/javascript">
<!--
var count = 0;
document.write("Starting Loop ");
while (count < 10) {
document.write("Current Count : " +
count + "<br />");
count++;
}
document.write("Loop stopped!");
//-->
</script>
<p>Set the variable to different value and
then try...</p>
</body>
</html>
45
JavaScript do-while loop statement
The do...while loop is similar to the while loop except that the condition check happens at the end of the loop. This
means that the loop will always be executed at least once, even if the condition is false.
Syntax:
do {
Statement(s) to be executed;
} while (expression);
<html>
<body>
<script type = "text/javascript">
<!-- var count = 0;
document.write("Starting Loop" + "<br
/>");
do {
document.write("Current Count : " +
count + "<br />");
count++;
} while (count < 5);
document.write ("Loop stopped!");
//-->
</script>
<p>Set the variable to different value and
then try...</p>
</body>
</html>
46
JavaScript for loop statement
The 'for' loop is the most compact form of
looping. It includes the following three
important parts −
 The loop initialization where we initialize
our counter to a starting value. The
initialization statement is executed before
the loop begins.
 The test statement which will test if a
given condition is true or not. If the
condition is true, then the code given
inside the loop will be executed, otherwise
the control will come out of the loop.
 The iteration statement where you can
increase or decrease your counter.
47
JavaScript for loop statement
Syntax:
for (initialization; test condition; iteration statement) {
Statement(s) to be executed if test condition is true
} <html>
<body>
<script type = "text/javascript">
<!-- var count;
document.write("Starting Loop" + "<br />");
for(count = 0; count < 10; count++) {
document.write("Current Count : " + count );
document.write("<br />");
}
document.write("Loop stopped!");//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
48
JavaScript for-in loop statement
The for...in loop is used to loop
through an object's properties. As
we have not discussed Objects yet,
you may not feel comfortable with
this loop.
Syntax:
for (variablename in object) {
statement or block to execute
}
In each iteration, one property
from object is assigned
to variablename and this loop
continues till all the properties of
the object are exhausted
<html>
<body>
<script type = "text/javascript">
<!-- var aProperty;
document.write("Navigator Object Properties<br
/> ");
for (aProperty in navigator) {
document.write(aProperty);
document.write("<br />");
}
document.write ("Exiting from the loop!");
//-->
</script>
<p>Set the variable to different object and then
try...</p>
</body>
</html>
49
JavaScript loop control
JavaScript provides full control to handle loops and switch statements. There may
be a situation when there is a need to come out of a loop without reaching its
bottom.
There may also be a situation when one want to skip a part of the code block and
start the next iteration of the loop.
To handle all such situations, JavaScript provides break and continue statements.
These statements are used to immediately come out of any loop or to start the next
iteration of any loop respectively.
50
JavaScript break control
The break statement "jumps out" of a loop
for (i = 0; i < 10; i++) {
if (i === 3) { break; }
text += "The number is " + i + "<br>";
}
Output:
The number is 0
The number is 1
The number is 2
51
JavaScript continue control
The continue statement tells the interpreter to immediately start the next iteration of the
loop and skip the remaining code block. When a continue statement is encountered,
the program flow moves to the loop check expression immediately and if the condition
remains true, then it starts the next iteration, otherwise the control comes out of the loop
for (i = 0; i < 10; i++) {
if (i === 3) { continue; }
text += "The number is " + i + "<br>";
}
Output:
The number is 0
The number is 1
The number is 2
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
52
JavaScript Array
JavaScript array is an object that represents a collection of similar type of elements.
There are 3 ways to construct array in JavaScript
1. By array literal
2. By creating instance of Array directly (using new keyword)
3. By using an Array constructor (using new keyword)
53
JavaScript Array
1) JavaScript array literal
The syntax of creating array using array literal is
given below:
var arrayname=[value1,value2.....valueN];
<script>
var emp=["Sonoo","Vimal","Ratan"];
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br/>");
}
</script>
2) JavaScript Array directly (new keyword)
The syntax of creating array directly is given below:
var arrayname=new Array();
Here, new keyword is used to create instance of array.
<script>
var i;
var emp = new Array();
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
3) JavaScript Array constructor (new keyword)
<script>
var emp=new Array("Jai","Vijay","Smith");
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
54
JavaScript Array Properties
S.No Property Description
1 Constructor Returns a reference to the array function that
created the object
2 Index The property represents the zero-based index of
the match in the string
3 Input This property is only present in arrays created by
regular expression matches.
4 Length Reflects the number of elements in an array.
5 prototype The prototype property allows you to add properties
and methods to an object.
55
JavaScript Array Example
<html>
<head>
<title>User-defined objects</title>
<script type = "text/javascript">
function book(title, author) {
this.title = title;
this.author = author;
}
</script>
</head>
<body>
<script type = "text/javascript">
var myBook = new book("Perl", "Mohtashim");
book.prototype.price = null;
myBook.price = 100;
document.write("Book title is : " + myBook.title + "<br>");
document.write("Book author is : " + myBook.author + "<br>");
document.write("Book price is : " + myBook.price + "<br>");
</script>
</body>
</html>
56
JavaScript Array Methods
S.No Methods Description
1 concat() Returns a new array comprised of this array joined with other array(s)
and/or value(s).
2 every() Returns true if every element in this array satisfies the provided
testing function.
3 indexOf() Returns the first (least) index of an element within the array equal to
the specified value, or -1 if none is found.
4 pop() Removes the last element from an array and returns that element.
5 push() Adds one or more elements to the end of an array and returns the
new length of the array.
6 reverse() Reverses the order of the elements of an array -- the first becomes
the last, and the last becomes the first.
7 sort() Sorts the elements of an array
8 toString() Returns a string representing the array and its elements.
There are different methods of array. Some important methods are as follows:
57
JavaScript Function
 A function is a group of reusable code which can be called anywhere in the
program. This eliminates the need of writing the same code again and again.
 It helps programmers in writing modular codes. It allow a programmer to divide a big
program into a number of small and manageable functions.
 The most common way to define a function in JavaScript is by using
the function keyword, followed by a unique function name, a list of parameters (that
might be empty), and a statement block surrounded by curly braces.
There are mainly two advantages of JavaScript functions.
1. Code reusability: We can call a function several times so it save coding.
2. Less coding: It makes our program compact. We don’t need to write many lines of
code each time to perform a common task.
58
Types of Function
There are basically two types of function:
1. System Defined (Built-in ) Function- It is built-in function provided by
javascript. Programmer can only call the system defined function wherever
required. There are different system defined function in javascript such as-
prompt(), alert(), confirm(), write(), trim(), etc.
2. User-defined function- Programmer can define their own function as per
requirement and then call the function wherever needed.
59
JavaScript Function contd…
Syntax for defining function
<script type = "text/javascript">
<!--
function functionname(parameter-list) {
statements
}
//-->
</script>
Example:
<script type = "text/javascript">
function Function_Demo() {
alert(“Function Demo");
}
</script>
60
JavaScript Function Calling
<html>
<head>
<script type = "text/javascript">
function FunctionDemo() {
document.write ("Hello! It’s a demo function");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = " FunctionDemo()" value = " Function Demo ">
</form>
</body>
</html>
61
Output of JavaScript Function Calling
In the above example, function call occurs on the click event of “Function Demo”
Button
62
JavaScript Function passing parameters
 In javascript, there is a facility
to pass different parameters
while calling a function.
 These passed parameters can
be captured inside the function
and any manipulation can be
done over those parameters.
 A function can take multiple
parameters separated by
comma.
<html>
<head>
<script type = "text/javascript">
function f_parameter(name, age) {
document.write (name + " is " + age + " years old.");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "f_parameter ('Zara',
7)" value = “Click Me">
</form>
</body>
</html>
63
Output of JavaScript Function Calling
In the above example, function call occurs on the click event of “Click” Button,
when function called, it passes parameter Zara and 7 to the function
64
Return statement
 A JavaScript function can have
an optional return statement.
 This is required if there is a
need to return a value from a
function.
 This statement should be the
last statement in a function.
 For example, you can pass two
numbers in a function and then
you can expect the function to
return their multiplication in your
calling program.
<html>
<head>
<script type = "text/javascript">
function multiply(f_num, s_num) {
return (f_num*s_num);
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick= "alert(multiply(6,7))"
value = “Multiply">
</form>
</body>
</html>
65
JavaScript Dialog Boxes
 JavaScript supports three important types of dialog boxes.
 These dialog boxes can be used to raise and alert, or to get confirmation on any input or
to have a kind of input from the users.
 Three dialog box supported by JavaScript are:
1. Alert Box
2. Confirmation Box
3. Prompt Box
66
JavaScript alert Boxes
 An alert dialog box is mostly used to give a warning message to the users.
 For example, if one input field requires to enter some text but the user does not provide
any input, then as a part of validation, one can use an alert box to give a warning
message.
 Nonetheless, an alert box can still be used for friendlier messages. Alert box gives only
one button "OK" to select and proceed.
67
JavaScript alert Box Example
<html>
<head>
<script type = "text/javascript">
function alert_demo() {
alert ("This is a warning message!");
document.write ("Alert Testing!");
}
</script>
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<input type = "button" value = "Click Me" onclick =
"alert_demo();" />
</form>
</body>
</html>
68
JavaScript confirmation Boxes
 A confirmation dialog box is mostly used to take user's consent on any option. It displays
a dialog box with two buttons: OK and Cancel.
 If the user clicks on the OK button, the window method confirm() will return true. If the
user clicks on the Cancel button, then confirm() returns false
69
JavaScript confirm() Box Example
<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>
70
JavaScript prompt() Boxes
 The prompt dialog box is very useful when there is need to pop-up a text box to get user
input. Thus, it enables to interact with the user. The user needs to fill in the field and then
click OK.
 This dialog box is displayed using a method called prompt() which takes two parameters:
(i) a label which you want to display in the text box and
(ii) a default string to display in the text box.
 This dialog box has two buttons: OK and Cancel. If the user clicks the OK button, the
window method prompt() will return the entered value from the text box. If the user clicks
the Cancel button, the window method prompt() returns null
71
JavaScript prompt() Box Example
<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>
72
JavaScript Event
 The change in the state of an object is known as an Event. In html, there are various
events which represents that some activity is performed by the user or by the browser.
When javascript code is included in HTML, js react over these events and allow the
execution. This process of reacting over the events is called Event Handling. Thus, js
handles the HTML events via Event Handlers.
 When the page loads, it is called an event. When the user clicks a button, that click too is
an event. Other examples include events like pressing any key, closing a window, resizing
a window, etc.
 Developers can use these events to execute JavaScript coded responses, which cause
buttons to close windows, messages to be displayed to users, data to be validated, and
virtually any other type of response imaginable.
 Events are a part of the Document Object Model (DOM) Level 3 and every HTML element
contains a set of events which can trigger JavaScript Code
73
Javascript Mouse Event
Event Performed Event Handler Description
click onclick When mouse click on an element
mouseover onmouseover When the cursor of the mouse comes over the
element
mouseout onmouseout When the cursor of the mouse leaves an
element
mousedown onmousedown When the mouse button is pressed over the
element
mouseup onmouseup When the mouse button is released over the
element
mousemove onmousemove When the mouse movement takes place.
74
JavaScript Form Event
Event
Performed
Event Handler Description
focus onfocus When the user focuses on an element
submit onsubmit When the user submits the form
blur onblur When the focus is away from a form
element
change onchange When the user modifies or changes the
value of a form element
75
JavaScript Window/ Document Event
Event
Performed
Event
Handler
Description
load onload When the browser finishes the loading of the page
unload onunload When the visitor leaves the current webpage, the browser
unloads it
resize onresize When the visitor resizes the window of the browser
JavaScript Keyboard Event
Event Performed Event Handler Description
Keydown & Keyup onkeydown & onkeyup When the user press and then release
the key

Mais conteúdo relacionado

Mais procurados (20)

javaScript.ppt
javaScript.pptjavaScript.ppt
javaScript.ppt
 
AngularJS for Beginners
AngularJS for BeginnersAngularJS for Beginners
AngularJS for Beginners
 
Javascript
JavascriptJavascript
Javascript
 
What is JavaScript? Edureka
What is JavaScript? EdurekaWhat is JavaScript? Edureka
What is JavaScript? Edureka
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
jQuery
jQueryjQuery
jQuery
 
Introduction of Html/css/js
Introduction of Html/css/jsIntroduction of Html/css/js
Introduction of Html/css/js
 
Brief History of JavaScript
Brief History of JavaScriptBrief History of JavaScript
Brief History of JavaScript
 
JavaScript
JavaScriptJavaScript
JavaScript
 
Xml Presentation-3
Xml Presentation-3Xml Presentation-3
Xml Presentation-3
 
jQuery
jQueryjQuery
jQuery
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
Java script ppt
Java script pptJava script ppt
Java script ppt
 
Html 5
Html 5Html 5
Html 5
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
Xpath presentation
Xpath presentationXpath presentation
Xpath presentation
 
Introduction to ajax
Introduction to ajaxIntroduction to ajax
Introduction to ajax
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to Javascript
 
HTML (Web) basics for a beginner
HTML (Web) basics for a beginnerHTML (Web) basics for a beginner
HTML (Web) basics for a beginner
 

Semelhante a Java script Basic

Java script by Act Academy
Java script by Act AcademyJava script by Act Academy
Java script by Act Academyactanimation
 
JAVA SCRIPT
JAVA SCRIPTJAVA SCRIPT
JAVA SCRIPTGo4Guru
 
Unit 4 Java script.pptx
Unit 4 Java script.pptxUnit 4 Java script.pptx
Unit 4 Java script.pptxGangesh8
 
JavaScript New Tutorial Class XI and XII.pptx
JavaScript New Tutorial Class XI and XII.pptxJavaScript New Tutorial Class XI and XII.pptx
JavaScript New Tutorial Class XI and XII.pptxrish15r890
 
Javascript - Ebook (A Quick Guide)
Javascript - Ebook (A Quick Guide)Javascript - Ebook (A Quick Guide)
Javascript - Ebook (A Quick Guide)sourav newatia
 
Session vii(java scriptbasics)
Session vii(java scriptbasics)Session vii(java scriptbasics)
Session vii(java scriptbasics)Shrijan Tiwari
 
Java Script - A New Look
Java Script - A New LookJava Script - A New Look
Java Script - A New Lookrumsan
 
Web programming UNIT II by Bhavsingh Maloth
Web programming UNIT II by Bhavsingh MalothWeb programming UNIT II by Bhavsingh Maloth
Web programming UNIT II by Bhavsingh MalothBhavsingh Maloth
 
WEB PROGRAMMING UNIT II BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT II BY BHAVSINGH MALOTHWEB PROGRAMMING UNIT II BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT II BY BHAVSINGH MALOTHBhavsingh Maloth
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascriptambuj pathak
 
Basics java scripts
Basics java scriptsBasics java scripts
Basics java scriptsch samaram
 
JavaScript - Getting Started.pptx
JavaScript - Getting Started.pptxJavaScript - Getting Started.pptx
JavaScript - Getting Started.pptxJonnJorellPunto
 
8.-Javascript-report powerpoint presentation
8.-Javascript-report powerpoint presentation8.-Javascript-report powerpoint presentation
8.-Javascript-report powerpoint presentationJohnLagman3
 
Basic JavaScript Tutorial
Basic JavaScript TutorialBasic JavaScript Tutorial
Basic JavaScript TutorialDHTMLExtreme
 

Semelhante a Java script Basic (20)

Javascript tutorial
Javascript tutorialJavascript tutorial
Javascript tutorial
 
Java script by Act Academy
Java script by Act AcademyJava script by Act Academy
Java script by Act Academy
 
JAVA SCRIPT
JAVA SCRIPTJAVA SCRIPT
JAVA SCRIPT
 
Unit 4 Java script.pptx
Unit 4 Java script.pptxUnit 4 Java script.pptx
Unit 4 Java script.pptx
 
JavaScript New Tutorial Class XI and XII.pptx
JavaScript New Tutorial Class XI and XII.pptxJavaScript New Tutorial Class XI and XII.pptx
JavaScript New Tutorial Class XI and XII.pptx
 
Javascript - Ebook (A Quick Guide)
Javascript - Ebook (A Quick Guide)Javascript - Ebook (A Quick Guide)
Javascript - Ebook (A Quick Guide)
 
Session vii(java scriptbasics)
Session vii(java scriptbasics)Session vii(java scriptbasics)
Session vii(java scriptbasics)
 
Java Script - A New Look
Java Script - A New LookJava Script - A New Look
Java Script - A New Look
 
Web programming UNIT II by Bhavsingh Maloth
Web programming UNIT II by Bhavsingh MalothWeb programming UNIT II by Bhavsingh Maloth
Web programming UNIT II by Bhavsingh Maloth
 
WEB PROGRAMMING UNIT II BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT II BY BHAVSINGH MALOTHWEB PROGRAMMING UNIT II BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT II BY BHAVSINGH MALOTH
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
Basics java scripts
Basics java scriptsBasics java scripts
Basics java scripts
 
Java scipt
Java sciptJava scipt
Java scipt
 
WEB TECHNOLOGIES JavaScript
WEB TECHNOLOGIES JavaScriptWEB TECHNOLOGIES JavaScript
WEB TECHNOLOGIES JavaScript
 
Java script
Java scriptJava script
Java script
 
JavaScript - Getting Started.pptx
JavaScript - Getting Started.pptxJavaScript - Getting Started.pptx
JavaScript - Getting Started.pptx
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
8.-Javascript-report powerpoint presentation
8.-Javascript-report powerpoint presentation8.-Javascript-report powerpoint presentation
8.-Javascript-report powerpoint presentation
 
Basic JavaScript Tutorial
Basic JavaScript TutorialBasic JavaScript Tutorial
Basic JavaScript Tutorial
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 

Mais de Jaya Kumari

Python data type
Python data typePython data type
Python data typeJaya Kumari
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to pythonJaya Kumari
 
Variables in python
Variables in pythonVariables in python
Variables in pythonJaya Kumari
 
Basic syntax supported by python
Basic syntax supported by pythonBasic syntax supported by python
Basic syntax supported by pythonJaya Kumari
 
Decision statements
Decision statementsDecision statements
Decision statementsJaya Kumari
 
Loop control statements
Loop control statementsLoop control statements
Loop control statementsJaya Kumari
 
Looping statements
Looping statementsLooping statements
Looping statementsJaya Kumari
 
Operators used in vb.net
Operators used in vb.netOperators used in vb.net
Operators used in vb.netJaya Kumari
 
Variable and constants in Vb.NET
Variable and constants in Vb.NETVariable and constants in Vb.NET
Variable and constants in Vb.NETJaya Kumari
 
Keywords, identifiers and data type of vb.net
Keywords, identifiers and data type of vb.netKeywords, identifiers and data type of vb.net
Keywords, identifiers and data type of vb.netJaya Kumari
 
Introduction to vb.net
Introduction to vb.netIntroduction to vb.net
Introduction to vb.netJaya Kumari
 
Frame class library and namespace
Frame class library and namespaceFrame class library and namespace
Frame class library and namespaceJaya Kumari
 
Introduction to .net
Introduction to .net Introduction to .net
Introduction to .net Jaya Kumari
 
Java script Advance
Java script   AdvanceJava script   Advance
Java script AdvanceJaya Kumari
 

Mais de Jaya Kumari (20)

Python data type
Python data typePython data type
Python data type
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Variables in python
Variables in pythonVariables in python
Variables in python
 
Basic syntax supported by python
Basic syntax supported by pythonBasic syntax supported by python
Basic syntax supported by python
 
Oops
OopsOops
Oops
 
Inheritance
InheritanceInheritance
Inheritance
 
Overloading
OverloadingOverloading
Overloading
 
Decision statements
Decision statementsDecision statements
Decision statements
 
Loop control statements
Loop control statementsLoop control statements
Loop control statements
 
Looping statements
Looping statementsLooping statements
Looping statements
 
Operators used in vb.net
Operators used in vb.netOperators used in vb.net
Operators used in vb.net
 
Variable and constants in Vb.NET
Variable and constants in Vb.NETVariable and constants in Vb.NET
Variable and constants in Vb.NET
 
Keywords, identifiers and data type of vb.net
Keywords, identifiers and data type of vb.netKeywords, identifiers and data type of vb.net
Keywords, identifiers and data type of vb.net
 
Introduction to vb.net
Introduction to vb.netIntroduction to vb.net
Introduction to vb.net
 
Frame class library and namespace
Frame class library and namespaceFrame class library and namespace
Frame class library and namespace
 
Introduction to .net
Introduction to .net Introduction to .net
Introduction to .net
 
Jsp basic
Jsp basicJsp basic
Jsp basic
 
Sgml and xml
Sgml and xmlSgml and xml
Sgml and xml
 
Java script Advance
Java script   AdvanceJava script   Advance
Java script Advance
 
Html form
Html formHtml form
Html form
 

Último

Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...apidays
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbuapidays
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusZilliz
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 

Último (20)

Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 

Java script Basic

  • 2. 2 What is JavaScript?  JavaScript was initially created to “make web pages alive”.  The programs in this language are called scripts.  They can be written right in a web page’s HTML and run automatically as the page loads.  Scripts are provided and executed as plain text.  They don’t need special preparation or compilation to run.  JavaScript is a lightweight, interpreted programming language.  It is designed for creating network-centric applications.  It is complimentary to and integrated with Java.  JavaScript is very easy to implement because it is integrated with HTML. It is open and cross-platform.
  • 3. 3 Why is it called ‘JavaScript’? When JavaScript was created, it initially had another name: “LiveScript”.  But Java was very popular at that time, so it was decided that positioning a new language as a “younger brother” of Java would help. But as it evolved, JavaScript became a fully independent language with its own specification called ECMAScript, and now it has no relation to Java at all. Today, JavaScript can execute not only in the browser, but also on the server, or actually on any device that has a special program called the JavaScript engine. The browser has an embedded engine sometimes called a “JavaScript virtual machine”.
  • 4. 4 Advantages of Java Script  Javascript is the most popular programming language in the world and that makes it a programmer’s great choice. Once you learnt Javascript, it helps to develop great front-end as well as back-end softwares using different Javascript based frameworks like jQuery, Node.JS etc.  Javascript is everywhere, it comes installed on every modern web browser and so to learn Javascript you really do not need any special environment setup. For example Chrome, Mozilla Firefox , Safari and every browser you know as of today, supports Javascript.  Javascript helps to create really beautiful and crazy fast websites. One can develop own website with a console like look and feel and give users the best Graphical User Experience.  JavaScript usage has now extended to mobile app development, desktop app development, and game development. This opens many opportunities for you as Javascript Programmer.  Due to high demand, there is tons of job growth and high pay for those who know JavaScript.  There are many useful Javascript frameworks and libraries available: Angular, React ,jQuery, Vue.js, Ext.js, Ember.js, Meteor, Mithril, Node.js, Polymer, Aurelia, Backbone.js
  • 5. 5 Applications of JavaScript  Client side validation - This is really important to verify any user input before submitting it to the server and Javascript plays an important role in validting those inputs at front-end itself.  Manipulating HTML Pages - Javascript helps in manipulating HTML page on the fly. This helps in adding and deleting any HTML tag very easily using javascript and modify your HTML to change its look and feel based on different devices and requirements.  User Notifications - You can use Javascript to raise dynamic pop-ups on the webpages to give different types of notifications to your website visitors.  Back-end Data Loading - Javascript provides Ajax library which helps in loading back-end data while you are doing some other processing. This really gives an amazing experience to your website visitors.  Presentations - JavaScript also provides the facility of creating presentations which gives website look and feel. JavaScript provides RevealJS and BespokeJS libraries to build a web- based slide presentations.  Server Applications - Node JS is built on Chrome's Javascript runtime for building fast and scalable network applications. This is an event based library which helps in developing very sophisticated server applications including Web Servers.
  • 6. 6 Limitations of JavaScript  Client-side JavaScript does not allow the reading or writing of files. This has been kept for security reason.  JavaScript cannot be used for networking applications because there is no such support available.  JavaScript doesn't have any multi-threading or multiprocessor capabilities
  • 7. 7 What makes JavaScript Unique? There are at least three great things about JavaScript: 1. Full integration with HTML/CSS. 2. Simple things are done simply. 3. Support by all major browsers and enabled by default. JavaScript is the only browser technology that combines these three things. That’s what makes JavaScript unique. That’s why it’s the most widespread tool for creating browser interfaces. That said, JavaScript also allows to create servers, mobile applications, etc.
  • 8. 8 JavaScript Syntax JavaScript can be implemented using JavaScript statements that are placed within the <script>... </script> HTML tags in a web page The <script> tag alerts the browser program to start interpreting all the text between these tags as a script <script language = "javascript" type = "text/javascript"> JavaScript code </script> The script tag takes two important attributes − Language − This attribute specifies what scripting language you are using. Typically, its value will be javascript. Although recent versions of HTML (and XHTML, its successor) have phased out the use of this attribute. Type − This attribute is what is now recommended to indicate the scripting language in use and its value should be set to "text/javascript".
  • 9. 9 Comments in JavaScript JavaScript supports both C-style and C++-style comments, Thus −  Any text between a // and the end of a line is treated as a comment and is ignored by JavaScript.  Any text between the characters /* and */ is treated as a comment. This may span multiple lines.  JavaScript also recognizes the HTML comment opening sequence <!--. JavaScript treats this as a single-line comment, just as it does the // comment.  The HTML comment closing sequence --> is not recognized by JavaScript so it should be written as //-->. <script language = "javascript" type = "text/javascript"> <!-- // This is a comment. It is similar to comments in C++ /* * This is a multi-line comment in JavaScript * It is very similar to comments in C Programming */ //--> </script>
  • 10. 10 JavaScript - Placement in HTML File There is a flexibility given to include JavaScript code anywhere in an HTML document. However the most preferred ways to include JavaScript in an HTML file are as follows −  Script in <head>...</head> section.  Script in <body>...</body> section.  Script in <body>...</body> and <head>...</head> sections.  Script in an external file and then include in <head>...</head> section
  • 11. 11 JavaScript in <head>----</head> section <html> <head> <script type = "text/javascript"> <!-- function sayHello() { alert("Hello World") } //--> </script> </head> <body> <input type = "button" onclick = "sayHello()" value = "Say Hello" /> </body> </html>
  • 12. 12 JavaScript in <body>…</body> section <html> <head> </head> <body> <script type = "text/javascript"> <!-- document.write("Hello World") //--> </script> <p>This is web page body </p> </body> </html>
  • 13. 13 JavaScript in <body> & <head> section <html> <head> <script type = "text/javascript"> <!-- function sayHello() { alert("Hello World") } //--> </script> </head> <body> <script type = "text/javascript"> <!-- document.write("Hello World") //--> </script> <input type = "button" onclick = "sayHello()" value = "Say Hello" /> </body> </html>
  • 14. 14 JavaScript in External file <html> <head> <script type = "text/javascript" src = "filename.js" ></script> </head> <body> ....... </body> </html> The script tag provides a mechanism to allow to store JavaScript in an external file and then include it into HTML files. To use JavaScript from an external file source, it is needed to write all JavaScript source code in a simple text file with the extension ".js" and then include that file as shown below.
  • 15. 15 JavaScript- variable A JavaScript variable is simply a name of storage location. Variables are used to store information. A variable's value can change during the script. JavaScript variables are case sensitive so watch upper case and lower case letters when referring to a variable. They also must start with letter or underscore. There are two types of variables in JavaScript : local variable and global variable. There are some rules while 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 we can use digits (0 to 9), for example value1.  JavaScript variables are case sensitive, for example x and X are different variables.  Declare a variable in JavaScript variable like this: var name;. This means, create variable name. Var is term used to declare a java and JavaScript variables. Assign a value to the variable like this: name="G. Danyeer";. This simply assigns the value G. Danyeer to the variable name. One can declare and assign a value in single statement as follows: var name = "G. Danyeer";
  • 16. 16 JavaScript- local variable A JavaScript local variable is declared inside block or function. It is accessible within the function or block only. For example: <script> function abc(){ var x=10;//local variable } </script> Or, <script> If(10<13){ var y=20;//JavaScript local variable } </script>
  • 17. 17 JavaScript- global variable A JavaScript global variable is accessible from any function. A variable i.e. declared outside the function or declared with window object is known as global variable. For example: <script> var data=200;//gloabal variable function a(){ document.writeln(data); } function b(){ document.writeln(data); } a();//calling JavaScript function b(); </script>
  • 18. 18 JavaScript- data types JavaScript provides different data types to hold different types of values. There are two types of data types in JavaScript.  Primitive data type  Non-primitive (reference) data type JavaScript is a dynamic type language, means there is no need to specify type of the variable because it is dynamically used by JavaScript engine. One need 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="Rahul";//holding string
  • 19. 19 JavaScript- Primitive Data Types 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
  • 20. 20 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
  • 21. 21 Empty Values An empty value has nothing to do with undefined. An empty string has both a legal value and a type. var car = ""; // The value is "", the typeof is "string" Undefined In JavaScript, a variable without a value, has the value undefined. The type is also undefined. var car; // Value is undefined, type is undefined Null In JavaScript null is "nothing". It is supposed to be something that doesn't exist. Unfortunately, in JavaScript, the data type of null is an object. var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"}; person = null; // Now value is null, but type is still an object JavaScript- Data Types
  • 22. 22 Javascript- Reserved Words abstract else instanceof switch boolean enum int synchronized break export interface this byte extends long throw case false native throws catch final new transient char finally null true class float package try const for private typeof continue function protected var debugger goto public void default if return volatile delete implements short while do import static with double in super
  • 23. 23 JavaScript- Operators JavaScript operators are symbols that are used to perform operations on operands. There are following types of operators in JavaScript. 1. Arithmetic Operators 2. Comparison (Relational) Operators 3. Bitwise Operators 4. Logical Operators 5. Assignment Operators 6. Special Operators
  • 24. 24 Javascript- Arithmetic Operators Arithmetic operators are used to perform arithmetic operations on the operands. The following operators are known as JavaScript arithmetic operators. 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
  • 25. 25 JavaScript- Comparison Operators The JavaScript comparison operator compares the two operands. The comparison operators are as follows: 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 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
  • 26. 26 JavaScript- Bitwise Operators The bitwise operators perform bitwise operations on operands. The bitwise operators are as follows: 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) = 40 >> Bitwise Right Shift (10>>2) = 2 >>> Bitwise Right Shift with Zero (10>>>2) = 2
  • 27. 27 JavaScript- Bitwise Operators The bitwise operators perform bitwise operations on operands. The bitwise operators are as follows: 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) = 40 >> Bitwise Right Shift (10>>2) = 2 >>> Bitwise Right Shift with Zero (10>>>2) = 2
  • 28. 28 JavaScript- Logical Operators The following operators are known as 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
  • 29. 29 JavaScript- Assignment Operators The following operators are known as 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=10; a*=20; Now a = 200 /= Divide and assign var a=10; a/=2; Now a = 5 %= Modulus and assign var a=10; a%=2; Now a = 0
  • 30. 30 JavaScript- Special Operators The following operators are known as 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) typeof 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.
  • 31. 31 JavaScript- typeof Operators The typeof operator is a unary operator that is placed before its single operand, which can be of any type. Its value is a string indicating the data type of the operand. The typeof operator evaluates to "number", "string", or "boolean" if its operand is a number, string, or boolean value and returns true or false based on the evaluation. Type String Returned by typeof Number "number" String "string" Boolean "boolean" Object "object" Function "function" Undefined "undefined" Null "object"
  • 32. 32 Example of typeof Operators <html> <body> <script type = "text/javascript"> <!-- var a = 10; var b = "String"; var linebreak = "<br />"; result = (typeof b == "string" ? "B is String" : "B is Numeric"); document.write("Result => "); document.write(result); document.write(linebreak); result = (typeof a == "string" ? "A is String" : "A is Numeric"); document.write("Result => "); document.write(result); document.write(linebreak); //--> </script> <p>Set the variables to different values and different operators and then try...</p> </body> </html>
  • 33. 33 Typecasting  Typecasting or coercion in simple term means to change the data type of a value to another data type like for example, integer to a string or a string to a boolean etc.  There are two types of coercion, implicit and explicit.  Implicit coercion is when there is automatic conversion of data type, where as When a developer expresses the intention to convert between types by writing the appropriate code, it’s called explicit type coercion (or type casting)  JavaScript only supports three type of conversion 1. to string 2. to boolean 3. to number  Number() converts to a Number, String() converts to a String, Boolean() converts to a Boolean.
  • 34. 34 String Typecasting  We can explicitly convert values to a string using the String() method .  Also JavaScript does a implicit string coercion when used with the+ operator. The most trivial example would be concatenation. val = 5 String(val) //explicit coercion '10' + val //105 not 15 and o/p is a String, implicit coercion  All other primitive values are converted to string naturally String(true) // 'true' String(false) // 'false' String(0) // '0' String(-0.99) // '-0.99' String(null) // "null" String(undefined) // "undefined"
  • 35. 35 Boolean Typecasting  To explicitly convert values to boolean we use the Boolean() method. Implicit conversion is done happens in logical context i.e if else statements and by logical operators ( || && !) .  The Boolean() type cast returns true when the value is a string with at least one character, a number other than 0, or an object ; it returns false when the value is an empty string, the number 0, undefined , or null . Boolean(0) //false Boolean(null) //false Boolean(undefined) //false Boolean('') //false Boolean('hi') //true Boolean(-1.2) //true Boolean(new Date()) //true  implicit Boolean(2 || 'hello') true Boolean(0 && new Date()) false if(2) { ... } true Boolean(0 == '0') true Boolean(0 === '0') false
  • 36. 36 Numeric Typecasting  To explicitly convert a value to a number we use the Number() method.  The number method converts to both integer and float.  Number() method calls two different methods, parseInt() and parseFloat() implicitly depending on the value. Number("5.6.7") //NaN parseInt("5.5.5") //5 parseFloat("5.5.5") //5.5  Comparison, bitwise and arithmetic operator uses implicit number conversion except for the arithmetic operator +, if there is a string, then this operator uses String()method instead for Number()
  • 37. 37 JavaScript if…else statement  JavaScript supports conditional statements which are used to perform different actions based on different conditions.  JavaScript supports the following forms of if..else statement − I. if statement II. if...else statement III. if...else if... statement.
  • 38. 38 JavaScript if…else statement  if statement The if statement is the fundamental control statement that allows JavaScript to make decisions and execute statements conditionally. Syntax: if (expression) { Statement(s) to be executed if expression is true }  Here a JavaScript expression is evaluated. If the resulting value is true, the given statement(s) are executed. If the expression is false, then no statement would be not executed. Most of the times, you will use comparison operators while making decisions. <html> <body> <script type = "text/javascript"> <!-- var age = 20; if( age > 18 ) { document.write("<b>Qualifies for driving</b>"); } //--> </script> <p>Set the variable to different value and then try...</p> </body> </html>
  • 39. 39 JavaScript if…else statement  If…else statement The 'if...else' statement is the next form of control statement that allows JavaScript to execute statements in a more controlled way. Syntax: if (expression) { Statement(s) to be executed if expression is true } else { Statement(s) to be executed if expression is false }  Here JavaScript expression is evaluated. If the resulting value is true, the given statement(s) in the ‘if’ block, are executed. If the expression is false, then the given statement(s) in the else block are executed. <html> <body> <script type = "text/javascript"> <!-- var age = 20; if( age > 18 ) { document.write("<b>Qualifies for driving</b>"); } else { document.write("<b>Does not qualify for driving</b>"); } //--> </script> <p>Set the variable to different value and then try...</p> </body> </html>
  • 40. 40 JavaScript if…else statement  If…else if... statement The if...else if... statement is an advanced form of if…else that allows JavaScript to make a correct decision out of several conditions. Syntax: if (expression 1) { Statement(s) to be executed if expression 1 is true } else if (expression 2) { Statement(s) to be executed if expression 2 is true } else if (expression 3) { Statement(s) to be executed if expression 3 is true } else { Statement(s) to be executed if no expression is true }  It is just a series of if statements, where each if is a part of the else clause of the previous statement. Statement(s) are executed based on the true condition, if none of the conditions is true, then the else block is executed <html> <body> <script type = "text/javascript"> <!-- var book = "maths"; if( book == "history" ) { document.write("<b>History Book</b>"); } else if( book == "maths" ) { document.write("<b>Maths Book</b>"); } else if( book == "economics" ) { document.write("<b>Economics Book</b>"); } else { document.write("<b>Unknown Book</b>"); }//--> </script> <p>Set the variable to different value and then try...</p> </body> </html>
  • 41. 41 JavaScript switch statement  The JavaScript switch statement is used to execute one code from multiple expressions. It is just like else if statement that we have learned in previous page. But it is convenient than if..else..if because it can be used with numbers, characters etc.  The objective of a switch statement is to give an expression to evaluate and several different statements to execute based on the value of the expression. The interpreter checks each case against the value of the expression until a match is found. If nothing matches, a default condition will be used.
  • 42. 42 JavaScript switch statement switch (expression) { case condition 1: statement(s) break; case condition 2: statement(s) break; ... case condition n: statement(s) break; default: statement(s) } The break statements indicate the end of a particular case. If they were omitted, the interpreter would continue executing each statement in each of the following cases. <html> <body> <script type = "text/javascript"> <!-- var grade = 'A'; document.write("Entering switch block<br />"); switch (grade) { case 'A': document.write("Good job<br />"); break; case 'B': document.write("Pretty good<br />"); break; case 'C': document.write("Passed<br />"); break; case 'D': document.write("Not so good<br />"); break; case 'F': document.write("Failed<br />"); break; default: document.write("Unknown grade<br />") } document.write("Exiting switch block"); //--> </script> <p>Set the variable to different value and then try...</p> </body> </html>
  • 43. 43 JavaScript loop statement The JavaScript loops are used to iterate the piece of code using for, while, do while or for-in loops. It makes the code compact. It is mostly used in array. There are four types of loops in JavaScript. 1. while loop 2. do-while loop 3. for loop 4. for-in loop
  • 44. 44 JavaScript while loop statement The purpose of a while loop is to execute a statement or code block repeatedly as long as an expression is true. Once the expression becomes false, the loop terminates Syntax: while (expression) { Statement(s) to be executed if expression is true } <html> <body> <script type = "text/javascript"> <!-- var count = 0; document.write("Starting Loop "); while (count < 10) { document.write("Current Count : " + count + "<br />"); count++; } document.write("Loop stopped!"); //--> </script> <p>Set the variable to different value and then try...</p> </body> </html>
  • 45. 45 JavaScript do-while loop statement The do...while loop is similar to the while loop except that the condition check happens at the end of the loop. This means that the loop will always be executed at least once, even if the condition is false. Syntax: do { Statement(s) to be executed; } while (expression); <html> <body> <script type = "text/javascript"> <!-- var count = 0; document.write("Starting Loop" + "<br />"); do { document.write("Current Count : " + count + "<br />"); count++; } while (count < 5); document.write ("Loop stopped!"); //--> </script> <p>Set the variable to different value and then try...</p> </body> </html>
  • 46. 46 JavaScript for loop statement The 'for' loop is the most compact form of looping. It includes the following three important parts −  The loop initialization where we initialize our counter to a starting value. The initialization statement is executed before the loop begins.  The test statement which will test if a given condition is true or not. If the condition is true, then the code given inside the loop will be executed, otherwise the control will come out of the loop.  The iteration statement where you can increase or decrease your counter.
  • 47. 47 JavaScript for loop statement Syntax: for (initialization; test condition; iteration statement) { Statement(s) to be executed if test condition is true } <html> <body> <script type = "text/javascript"> <!-- var count; document.write("Starting Loop" + "<br />"); for(count = 0; count < 10; count++) { document.write("Current Count : " + count ); document.write("<br />"); } document.write("Loop stopped!");//--> </script> <p>Set the variable to different value and then try...</p> </body> </html>
  • 48. 48 JavaScript for-in loop statement The for...in loop is used to loop through an object's properties. As we have not discussed Objects yet, you may not feel comfortable with this loop. Syntax: for (variablename in object) { statement or block to execute } In each iteration, one property from object is assigned to variablename and this loop continues till all the properties of the object are exhausted <html> <body> <script type = "text/javascript"> <!-- var aProperty; document.write("Navigator Object Properties<br /> "); for (aProperty in navigator) { document.write(aProperty); document.write("<br />"); } document.write ("Exiting from the loop!"); //--> </script> <p>Set the variable to different object and then try...</p> </body> </html>
  • 49. 49 JavaScript loop control JavaScript provides full control to handle loops and switch statements. There may be a situation when there is a need to come out of a loop without reaching its bottom. There may also be a situation when one want to skip a part of the code block and start the next iteration of the loop. To handle all such situations, JavaScript provides break and continue statements. These statements are used to immediately come out of any loop or to start the next iteration of any loop respectively.
  • 50. 50 JavaScript break control The break statement "jumps out" of a loop for (i = 0; i < 10; i++) { if (i === 3) { break; } text += "The number is " + i + "<br>"; } Output: The number is 0 The number is 1 The number is 2
  • 51. 51 JavaScript continue control The continue statement tells the interpreter to immediately start the next iteration of the loop and skip the remaining code block. When a continue statement is encountered, the program flow moves to the loop check expression immediately and if the condition remains true, then it starts the next iteration, otherwise the control comes out of the loop for (i = 0; i < 10; i++) { if (i === 3) { continue; } text += "The number is " + i + "<br>"; } Output: The number is 0 The number is 1 The number is 2 The number is 4 The number is 5 The number is 6 The number is 7 The number is 8 The number is 9
  • 52. 52 JavaScript Array JavaScript array is an object that represents a collection of similar type of elements. There are 3 ways to construct array in JavaScript 1. By array literal 2. By creating instance of Array directly (using new keyword) 3. By using an Array constructor (using new keyword)
  • 53. 53 JavaScript Array 1) JavaScript array literal The syntax of creating array using array literal is given below: var arrayname=[value1,value2.....valueN]; <script> var emp=["Sonoo","Vimal","Ratan"]; for (i=0;i<emp.length;i++){ document.write(emp[i] + "<br/>"); } </script> 2) JavaScript Array directly (new keyword) The syntax of creating array directly is given below: var arrayname=new Array(); Here, new keyword is used to create instance of array. <script> var i; var emp = new Array(); emp[0] = "Arun"; emp[1] = "Varun"; emp[2] = "John"; for (i=0;i<emp.length;i++){ document.write(emp[i] + "<br>"); } </script> 3) JavaScript Array constructor (new keyword) <script> var emp=new Array("Jai","Vijay","Smith"); for (i=0;i<emp.length;i++){ document.write(emp[i] + "<br>"); } </script>
  • 54. 54 JavaScript Array Properties S.No Property Description 1 Constructor Returns a reference to the array function that created the object 2 Index The property represents the zero-based index of the match in the string 3 Input This property is only present in arrays created by regular expression matches. 4 Length Reflects the number of elements in an array. 5 prototype The prototype property allows you to add properties and methods to an object.
  • 55. 55 JavaScript Array Example <html> <head> <title>User-defined objects</title> <script type = "text/javascript"> function book(title, author) { this.title = title; this.author = author; } </script> </head> <body> <script type = "text/javascript"> var myBook = new book("Perl", "Mohtashim"); book.prototype.price = null; myBook.price = 100; document.write("Book title is : " + myBook.title + "<br>"); document.write("Book author is : " + myBook.author + "<br>"); document.write("Book price is : " + myBook.price + "<br>"); </script> </body> </html>
  • 56. 56 JavaScript Array Methods S.No Methods Description 1 concat() Returns a new array comprised of this array joined with other array(s) and/or value(s). 2 every() Returns true if every element in this array satisfies the provided testing function. 3 indexOf() Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found. 4 pop() Removes the last element from an array and returns that element. 5 push() Adds one or more elements to the end of an array and returns the new length of the array. 6 reverse() Reverses the order of the elements of an array -- the first becomes the last, and the last becomes the first. 7 sort() Sorts the elements of an array 8 toString() Returns a string representing the array and its elements. There are different methods of array. Some important methods are as follows:
  • 57. 57 JavaScript Function  A function is a group of reusable code which can be called anywhere in the program. This eliminates the need of writing the same code again and again.  It helps programmers in writing modular codes. It allow a programmer to divide a big program into a number of small and manageable functions.  The most common way to define a function in JavaScript is by using the function keyword, followed by a unique function name, a list of parameters (that might be empty), and a statement block surrounded by curly braces. There are mainly two advantages of JavaScript functions. 1. Code reusability: We can call a function several times so it save coding. 2. Less coding: It makes our program compact. We don’t need to write many lines of code each time to perform a common task.
  • 58. 58 Types of Function There are basically two types of function: 1. System Defined (Built-in ) Function- It is built-in function provided by javascript. Programmer can only call the system defined function wherever required. There are different system defined function in javascript such as- prompt(), alert(), confirm(), write(), trim(), etc. 2. User-defined function- Programmer can define their own function as per requirement and then call the function wherever needed.
  • 59. 59 JavaScript Function contd… Syntax for defining function <script type = "text/javascript"> <!-- function functionname(parameter-list) { statements } //--> </script> Example: <script type = "text/javascript"> function Function_Demo() { alert(“Function Demo"); } </script>
  • 60. 60 JavaScript Function Calling <html> <head> <script type = "text/javascript"> function FunctionDemo() { document.write ("Hello! It’s a demo function"); } </script> </head> <body> <p>Click the following button to call the function</p> <form> <input type = "button" onclick = " FunctionDemo()" value = " Function Demo "> </form> </body> </html>
  • 61. 61 Output of JavaScript Function Calling In the above example, function call occurs on the click event of “Function Demo” Button
  • 62. 62 JavaScript Function passing parameters  In javascript, there is a facility to pass different parameters while calling a function.  These passed parameters can be captured inside the function and any manipulation can be done over those parameters.  A function can take multiple parameters separated by comma. <html> <head> <script type = "text/javascript"> function f_parameter(name, age) { document.write (name + " is " + age + " years old."); } </script> </head> <body> <p>Click the following button to call the function</p> <form> <input type = "button" onclick = "f_parameter ('Zara', 7)" value = “Click Me"> </form> </body> </html>
  • 63. 63 Output of JavaScript Function Calling In the above example, function call occurs on the click event of “Click” Button, when function called, it passes parameter Zara and 7 to the function
  • 64. 64 Return statement  A JavaScript function can have an optional return statement.  This is required if there is a need to return a value from a function.  This statement should be the last statement in a function.  For example, you can pass two numbers in a function and then you can expect the function to return their multiplication in your calling program. <html> <head> <script type = "text/javascript"> function multiply(f_num, s_num) { return (f_num*s_num); } </script> </head> <body> <p>Click the following button to call the function</p> <form> <input type = "button" onclick= "alert(multiply(6,7))" value = “Multiply"> </form> </body> </html>
  • 65. 65 JavaScript Dialog Boxes  JavaScript supports three important types of dialog boxes.  These dialog boxes can be used to raise and alert, or to get confirmation on any input or to have a kind of input from the users.  Three dialog box supported by JavaScript are: 1. Alert Box 2. Confirmation Box 3. Prompt Box
  • 66. 66 JavaScript alert Boxes  An alert dialog box is mostly used to give a warning message to the users.  For example, if one input field requires to enter some text but the user does not provide any input, then as a part of validation, one can use an alert box to give a warning message.  Nonetheless, an alert box can still be used for friendlier messages. Alert box gives only one button "OK" to select and proceed.
  • 67. 67 JavaScript alert Box Example <html> <head> <script type = "text/javascript"> function alert_demo() { alert ("This is a warning message!"); document.write ("Alert Testing!"); } </script> </head> <body> <p>Click the following button to see the result: </p> <form> <input type = "button" value = "Click Me" onclick = "alert_demo();" /> </form> </body> </html>
  • 68. 68 JavaScript confirmation Boxes  A confirmation dialog box is mostly used to take user's consent on any option. It displays a dialog box with two buttons: OK and Cancel.  If the user clicks on the OK button, the window method confirm() will return true. If the user clicks on the Cancel button, then confirm() returns false
  • 69. 69 JavaScript confirm() Box Example <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>
  • 70. 70 JavaScript prompt() Boxes  The prompt dialog box is very useful when there is need to pop-up a text box to get user input. Thus, it enables to interact with the user. The user needs to fill in the field and then click OK.  This dialog box is displayed using a method called prompt() which takes two parameters: (i) a label which you want to display in the text box and (ii) a default string to display in the text box.  This dialog box has two buttons: OK and Cancel. If the user clicks the OK button, the window method prompt() will return the entered value from the text box. If the user clicks the Cancel button, the window method prompt() returns null
  • 71. 71 JavaScript prompt() Box Example <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>
  • 72. 72 JavaScript Event  The change in the state of an object is known as an Event. In html, there are various events which represents that some activity is performed by the user or by the browser. When javascript code is included in HTML, js react over these events and allow the execution. This process of reacting over the events is called Event Handling. Thus, js handles the HTML events via Event Handlers.  When the page loads, it is called an event. When the user clicks a button, that click too is an event. Other examples include events like pressing any key, closing a window, resizing a window, etc.  Developers can use these events to execute JavaScript coded responses, which cause buttons to close windows, messages to be displayed to users, data to be validated, and virtually any other type of response imaginable.  Events are a part of the Document Object Model (DOM) Level 3 and every HTML element contains a set of events which can trigger JavaScript Code
  • 73. 73 Javascript Mouse Event Event Performed Event Handler Description click onclick When mouse click on an element mouseover onmouseover When the cursor of the mouse comes over the element mouseout onmouseout When the cursor of the mouse leaves an element mousedown onmousedown When the mouse button is pressed over the element mouseup onmouseup When the mouse button is released over the element mousemove onmousemove When the mouse movement takes place.
  • 74. 74 JavaScript Form Event Event Performed Event Handler Description focus onfocus When the user focuses on an element submit onsubmit When the user submits the form blur onblur When the focus is away from a form element change onchange When the user modifies or changes the value of a form element
  • 75. 75 JavaScript Window/ Document Event Event Performed Event Handler Description load onload When the browser finishes the loading of the page unload onunload When the visitor leaves the current webpage, the browser unloads it resize onresize When the visitor resizes the window of the browser JavaScript Keyboard Event Event Performed Event Handler Description Keydown & Keyup onkeydown & onkeyup When the user press and then release the key