javascript_tutorial
javascript_tutorial
Audience
applications.
Prerequisites
All the content and graphics published in this e-book are the property of Tutorials
Point (I) Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy,
distribute or republish any contents or apart of contents of this e-book in any
Westrivetoupdatethecontentsofourwebsiteandtutorialsastimelyandas
contact@tutorialspoint.com
:
Table of Contents
Audience....
Prerequisites...
Table of Contents
-
1. JAVASCRIPT - OvervieW.
What is JavaScript?
2
Client-Side JavaScript...
Advantages of JavaScript..
3
3
Limitations of JavasScript...
3
JavaScript Development Tools.
.
4 5
Where is JavaScript Today?...
5
Your First JavaScript Code
Case Sensitivity...
.
Comments in JavaScript ... 19
0
9 1
3. JAVASCRIPT - Enabling 0
JavaScript in Chrome
JavaScript in Opera ..
4.JAVASCRIPT-Placement.. .12
13
JavaScript Datatypes.
JavaScript Variables...
6 JAVASCRIPT - Operators
.
What is an Operator?
Arithmetic Operators...
Comparison Operators
.16
16
..16
17
18
19
.20
.20
.20
23
.26
ii
Bitwise Operators... 28
Miscellaneous Operators... 34
if Statement. 39
8. JAVASCRIPT - Switch-Case . 43
Flow Chart 43
onmouseoverandonmouseout. .76
ili
>tutorialspoint
16. JAVASCRIPT -Page Redirect .89
MAX_VALUE .113
MIN_VALUE ..114
NaN. ...115
POSITIVE_INFINITY ..118
Prototype.. .119
constructor . ...121
toExponential () ..122
toFixed 0. ..124
toLocaleString () .125
toPrecision ..126
valueOf () ..128
constructor (. ...130
Prototype... ...131
toSource () ..133
valueOf () .135
iv
23. JAVASCRIPT - String.. .137
constructor ...137
Length .138
Prototype.. ...139
charAt(). ...142
contact () ...144
lastIndexOf () ..147
localeCompare () ...148
match ()
slice () ...154
toLocaleLowerCase() ...158
toLocaleUppereCase () ...159
toUpperCase () ...162
valueOf () . ...163
big().. ....166
bold () ...168
fontColor () ...169
fontsize () ....170
italics () ...171
small () . ...173
sub(). .175
constructor .179
length.. .180
Prototype.. ..181
concat () - ..184
forEach 0 .190
>tutorialspoint
indexOf 0 .192
join () .195
lastIndexOf 0) ...196
map () ...199
pop () ...201
reduce () .204
reduceRight0 .207
reverse () ....211
shift () ..212
slice () .213
sort () ...216
splice () .217
unshift () .. .220
25.JAVASCRIPT-Date .222
constructor . .223
Prototype... .224
Date().. ...229
getDate(). .229
getDay() . ..230
getFullYear() .231
getHours(). .232
getMilliseconds() .233
getMinutes () ..234
getMonth () .235
getSeconds () .236
getTime () .236
getTimezoneOffset () .237
getUTCDate () . ..238
getUTCHours () . .241
getUTCMinutes () .243
getUTCSeconds () ..244
getYear () .245
setDate () . .246
setHours () ..248
setMilliseconds () .249
setMinutes () .250
setSeconds () .252
vi
>tutorialspoint
setUTCDate 0 .254
setUTCFullYear () .255
setUTCHours () . .257
setUTCMilliseconds () .258
setYear () .262
toDateString () ...263
toLocaleDateString () .265
tolocaleDateString () ...266
toLocaleFormat () ...266
tolocaleString () .267
toSource () ...2.69
toUTCString () .272
valeOf () . ...273
Date.UTC () . .275
Math-E. .278
Math-LN2. .279
Math-LN10. ..279
Math-LOG2E . ..280
Math-LOG10E .281
Math-PI.. .282
Math-SQRT1 2 .283
Math-SQRT2 ..283
abs () .285
acos0 ..287
asin () ..288
atan () .289
atan2 () .290
ceil ) ..292
cos () .293
exp(. .295
floor() .296
log() ..297
max () .298
pow() .301
random() .302
round () .304
vii
>tutorialspoint
sin .305
sqrt ) .306
tan () .307
Brackets .310
Quantifiers.... ..311
Metacharacters .313
constructor ..314
global.. ..315
lastIndex . .318
multiline.. ..319
source ..320
exec) .322
test () .323
toSource () ..324
32.JAVASCRIPT-Multimedia.. .365
vili
Checking for Plug-Ins.. 366
ix
Part 1: JavaScript Basics
10
>tutorialspoint
6IMP
1.JAVASCRIPT-OVERVIEW
What is JavaScript?
TheECMA-262SpecificationdefinedastandardversionofthecoreJavaScript
language.
Client-Side JavaScript
Client-sideJavaScriptisthemostcommonformofthelanguage.Thescriptshould
the browser.
The JavaScript client-side mechanism provides many advantages over traditional CGI
11
TheJavaScriptcodeisexecutedwhentheusersubmitstheform,andonlyif all the
Advantages of JavaScript
server.
Limitations of JavaScript
Client-side JavaScript does not allow the reading or writing of files. This has
been kept for security reason.
support available.
development tools.You can start with a simple text editor such as Notepad. Since it
12
is an interpreted language inside the contextof a web browser,you don't even need
to buy a compiler.
·MicrosoftFrontPage:MicrosofthasdevelopedapopularHTMLeditor called
wellwithdatabases,and conformstonewstandardssuchasXHTMLandXML.
effectively.
ThespecificationforJavaScript2.0canbefoundonthefollowingsite:
http://www.ecmascript.org/
standard, although both the languages still support the features that are not a part
of the standard.
13
2.JAVASCRIPT - SYNTAX
web page,but it is normally recommended that you should keep it within the <head>
tags.
<script ...>
JavaScript code
</script>
JavaScript code
</script>
comment that surrounds our JavaScript code. This is to save our code from a browser
that does not support JavaScript.The comment ends with a "//-->".Here "//"
14
the end of the HTMLcommentasa piece of JavaScriptcode.Next,we calla
functiondocument.writewhichwritesastringintoourHTMLdocument.
This function can be used to write text, HTML, or both. Take a look at the following
code.
<htm1>
<body>
<!--
//-->
</script>
</body>
</htm1>
Hello World!
formatand indentyourprogramsinaneatandconsistentwaythatmakesthecode
semicolonifeachofyourstatementsareplacedonaseparateline.Forexample,the
15
>tutorialspoint
<!-
-
var1 = 10
var2 = 20
//--
>
</script>
<!--
//--
>
</script>
Case Sensitivity
variables, function names, and any other identifiers must always be typed with a
consistentcapitalizationofletters.
Comments in JavaScript
ignored by JavaScript.
16
The HTML comment closing sequence --> is not recognized by JavaScript so it
should be written as //-->.
Example
ThefollowingexampleshowshowtousecommentsinJavaScript.
<!--
/*
*/
//-->
</script>
17
>tutorialspoint
3.JAVASCRIPT-ENABLING
All the modern browsers come with built-in support for JavaScript. Frequently, you
To disable JavaScript support in your Internet Explorer, you need to select Disable
JavaScript in Firefox
'
18
JavaScript in Chrome
Select Settings.
JavaScript in Opera
To disable JavaScript support in Opera, you should not select the Enable
JavaScript checkbox.
If you have to do something important using JavaScript, then you can display a
You can add a noscript block immediately after the script block as follows:
<htm1>
<body>
<!--
19
>tutorialspoint
document.write ("Hello World!")
//-->
</script>
<noscript>
</noscript>
</body>
</htm1>
Now, if the user's browser does not support JavaScript or JavaScript is not enabled,
20
>tutorialspoint
4.JAVASCRIPT- PLACEMENT
In the following section, we will see how we can place JavaScript in an HTML file in
different ways.
If you want to have a script run on some event, such as when a user clicks
<htm1>
<head>
<!--
function sayHello() {
alert("Hello World")
//-->
</script>
</head>
<body>
21
>tutorialspoint
</body>
</htm1>
Say Hello
If you need a script to run as the page loads so that the script generates content in
you would not have any function defined using JavaScript. Take a look at the following
code.
<htm1>
<head>
</head>
<body>
<script type="text/javascript">
<!--
document.write("Hello World")
//-->
</script>
</body>
</htm1>
Hello World
22
>tutorialspoint
This is web page body
You can put your JavaScript code in <head> and <body> section altogether as
follows.
<htm1>
<head>
<script type="text/javascript">
<!--
function sayHello() {
alert("Hello World")
//-->
</script>
</head>
<body>
<script type="text/javascript">
<!--
document.write("Hello World")
//-->
</script>
</body>
</htm1>
HelloWorld
Say Hello
23
>tutorialspoint
JavaScript in External File
a site.
You are not restricted to be maintaining identical code in multiple HTML files.
ThescripttagprovidesamechanismtoallowyoutostoreJavaScriptinanexternal
file and then include it into your HTML files.
HereisanexampletoshowhowyoucanincludeanexternalJavaScriptfileinyour
<htm1>
<head>
</head>
<body>
</body>
</htm1>
source code in a simple text file with the extension ".js" and then include that file as
shown above.
function sayHello() {
alert("Hello World")
24
- >tutorialspoint
1
5.JAVASCRIPT - VARIABLES
JavaScript Datatypes
JavaScript also defines two trivial data types, null and undefined, each of which
defines only a single value. In addition to these primitive data types, JavaScript
separate chapter.
Note:Javadoesnotmakeadistinctionbetweenintegervaluesandfloating-point
JavaScript Variables
Like many other programming languages, JavaScript has variables. Variables can be
thought of as named containers.You can place data into these containers and then
Before you use a variable in a JavaScript program, you must declare it. Variables are
declared with the var keyword as follows
<script type="text/javascript">
<!--
var money;
var name;
25
>tutorialspoint
//-->
</script>
<!--
//-->
</script>
Storingavalueinavariableiscalledvariableinitialization.Youcandovariable
initialization at the time of variable creation or at a later point in time when you need
that variable.
For instance,you might create a variable named money and assign the value
2000.50 to it later. For another variable, you can assign a value at the time of
initialization as follows.
<script type="text/javascript"
<!--
var money;
money = 2000.50;
I--
</script>
Note: Use the var keyword only for declaration or initialization, once for the life of
JavaScriptisuntypedlanguage.ThismeansthataJavaScriptvariablecanholda
value of any data type. Unlike many other languages, you don't have to tell JavaScript
of it automatically.
26
JavaScript Variable Scope
Local Variables:A local variable will bevisible only within a function where it
Within the body of a function, a local variable takes precedence over a global variable
withthesamename.Ifyoudeclarealocalvariableorfunctionparameterwiththe
samenameasaglobalvariable,youeffectivelyhidetheglobalvariable.Takealook
<script type="text/javascript">
<!--
function checkscope( ) {
document.write(myVar);
//-->
</script>
Local
27
>tutorialspoint
You should not use any of the JavaScript reserved keywords as a variable
A list of all the reserved words in JavaScript are given in the following table. They
cannotbeusedasJavaScriptvariables,functions,methods,looplabels,oranyobject
names.
double in super
28
>tutorialspoint
6.JAVASCRIPT - OPERATORS
What is an Operator?
operators.
Arithmetic Operators
Comparison Operators
Assignment Operators
Arithmetic Operators
+ (Addition)
- (Subtraction)
2 Subtractsthesecond operandfromthefirst
29
>tutorialspoint
* (Multiplication)
/ (Division)
% (Modulus)
++ (Increment)
-- (Decrement)
그
Decreases an integer value by one
give "a10".
Example
<htm1>
<body>
<script type="text/javascript">
<!--
var a = 33;
30
>tutorialspoint
var b = 10;
var c = "Test";
document.write("a + b = ");
result = a + b;
document.write(result);
document.write(linebreak);
document.write("a - b = ");
result = a - b;
document.write(result);
document.write(linebreak);
document.write("a / b = ");
result = a / b;
document.write(result);
document.write(linebreak);
document.write("a % b = ");
result = a % b;
document.write(result);
document.write(linebreak);
document.write("a + b + c = ")
result = a + b + c;
document.write(result);
document.write(linebreak);
31
>tutorialspoint
a = a++;
document.write("a++ = ");
result = a++;
document.write(result);
document.write(linebreak);
b = b--;
document.write("b-- = ");
result = b--;
document.write(result);
document.write(linebreak);
//-->
</script>
</body>
</htm1>
Output
a+b=43
a-b=23
a/b=3.3
a%b=3
a + b + c = 43Test
a++ = 33
b-- = 10
32
>tutorialspoint
Comparison Operators
AssumevariableAholds10andvariableBholds20,then:
== (Equal)
1
the condition becomes true.
!= (Not Equal)
Checks if the value of two operands are equal or not, if the values
2
are not equal, then the condition becomes true.
Ex: (A != B) is true.
Checksifthevalueoftheleftoperandisgreaterthanthevalueof
3
true.
33
>tutorialspoint
<= (Less than or Equal to)
Checksifthevalueoftheleftoperandislessthanorequaltothe
6
value of theright operand,ifyes,then the conditionbecomes true.
Example
<htm1>
<body
>
<script type="text/javascript">
<!--
var a = 10;
var b = 20;
result = (a == b);
document.write(result);
document.write(linebreak);
document.write(result);
document.write(linebreak);
document.write(result);
document.write(linebreak);
34
>tutorialspoint
document.write("(a != b) => ");
result = (a != b);
document.write(result);
document.write(linebreak);
document.write(result);
document.write(linebreak);
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Setthevariablestodifferentvaluesanddifferentoperators andthen
try...</p>
</body>
</htm1>
Output
(a == b) => false
(a ,b)-) false
(a ノ= b)=> false
35
>tutorialspoint
(a <= b) => true
try...
Logical Operators
AssumevariableAholds10 andvariableBholds20,then:
1 If both the operands are non-zero, then the condition becomes true.
I1 (Logical OR)
Ex: (A II B) is true.
! (Logical NOT)
Example
36
>tutorialspoint
<htm1>
<body>
<script type="text/javascript">
<!--
var a = true;
var b = false;
document.write(result);
document.write(linebreak);
result = (a Il b);
document.write(result);
document.write(linebreak);
document.write(result);
document.write(linebreak) ;
//-->
</script>
37
>tutorialspoint
<p>Setthevariablestodifferentvaluesanddifferentoperators andthen
try...</p>
</body>
</htm1>
Output
(a II b)- true
!(a && b) => true
try...
Bitwise Operators
AssumevariableAholds2andvariableBholds3,then:
Ex: (A & B) is 2.
I (BitWise OR)
2 ItperformsaBooleanORoperationoneachbitofitsintegerarguments
Ex: (A B) is 3.
3 A
(Bitwise XOR)
38
>tutorialspoint
two is true, but not both.
Ex: (A B) is 1.
(Bitwise Not)
It moves all the bits in its first operand to the left by the number of places
specified in the second operand. New bits are filled with zeros. Shifting a
5
Ex: (A<< 1) is 4.
6
number of bits specified by the right operand.
Ex: (A >> 1) is 1.
7
on the left are always zero.
Ex: (A >>> 1) is 1.
Example
<htm1>
<body>
<script type="text/javascript">
39
>tutorialspoint
<!--
document.write(result);
document.write(linebreak);
result = (a I b);
document.write(result);
document.write(linebreak);
result = (a b);
document.write(result);
document.write(linebreak);
result = (b);
document.write(result);
document.write(linebreak);
document.write(result);
document.write(linebreak);
40
>tutorialspoint
document.write("(a >> b) => ");
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then
try...</p>
</body>
</htm1>
Output
(а&b)-2
(а l b)=?
(ab)=1
(b)=)-4
(a くく b)=)16
(a b)ミ û
try...
Assignment Operators
- (Simple Assignment )
1
41
>tutorialspoint
Ex: C = A + B will assign the value of A + B into C
It adds the right operand to theleft operand and assigns the result to the
2
left operand.
Ex: C += A is equivalent to C = C + A
It subtracts the right operand from theleft operand and assigns theresult
3
to the left operand.
Ex: C -= A is equivalent to C = C - A
4
to the left operand.
Ex: C *= A is equivalent to C = C * A
5
the left operand.
Ex: C /= A is equivalent to C = C / A
It takes modulus using two operands and assigns the result to the left
6
operand.
Ex: C %= A is equivalent to C = C % A
&=,1= and =.
Example
42
>tutorialspoint
<htm1>
<body>
<script type="text/javascript">
<!--
var a = 33;
var b = 10;
result = (a = b);
document.write(result);
document.write(linebreak);
result = (a += b);
document.write(result);
document.write(linebreak);
result = (a -= b);
document.write(result);
document.write(linebreak);
result - Qa *- b):
document.write(result);
document.write(linebreak);
43
>tutorialspoint
document.write("Value of a =>(a /= b) =>");
result = (a /= b);
document.write(result);
document.write(linebreak);
result = (a %= b);
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Setthevariablestodifferentvaluesanddifferentoperators andthen
try...</p>
</body>
</htm1>
Output
Setthevariablestodifferentvaluesanddifferentoperatorsandthen
try...
44
>tutorialspoint
Miscellaneous Operators
We will discuss two operators here that are quite useful in JavaScript: the
Conditional Operator (? :)
The conditional operator first evaluates an expression for a true or false value and
thenexecutesoneof thetwogivenstatementsdependingupon theresultof the
evaluation.
? : (Conditional )
1
Example
Try the following code to understand how the Conditional Operator works in
JavaScript.
<htm1>
<body>
<script type="text/javascript">
<!--
var a = 10;
var b = 20;
document.write(result);
document.write(linebreak);
document.write("((a<b)?100:200)=>");
45
>tutorialspoint
result = (a < b) ? 100 : 200;
document.write(result);
document.write(linebreak);
//-->
</script>
try...</p>
</body>
</htm1>
Output
try...
typeof Operator
The typeof operator is a unary operator that is placed before its single operand,
whichcanbeof anytype.Itsvalueis astringindicating thedatatype ofthe operand
number, string,or boolean value and returns true or false based on the evaluation.
Number "number"
String "string"
46
>tutorialspoint
Boolean "boolean"
Object "object"
Function "function"
Undefined "undefined"
Null "object"
Example
<htm1>
<body>
<script type="text/javascript">
<!--
var a = 10;
var b = "String";
document.write(result);
document.write(linebreak);
document.write(result);
document.write(linebreak);
47
>tutorialspoint
6IM P
//-->
</script>
<p>Set the variables to different values and different operators and then
try...</p>
</body>
</htm1>
Output
Setthevariablestodifferentvaluesanddifferentoperatorsandthen
try...
48
>tutorialspoint
End of ebook preview
49
>tutorialspoint
6IMP