0% found this document useful (0 votes)
9 views

javascript_tutorial

Y see

Uploaded by

raheemabdur881
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

javascript_tutorial

Y see

Uploaded by

raheemabdur881
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 51

About the Tutorial

is open and cross-platform.

Audience

thebasicfunctionalityof JavaScript tobuilddynamic webpages andweb

applications.

Prerequisites

Forthis tutorial,it isassumed that the reader have a priorknowledge of HTML


coding. It would help if the reader had some prior exposure to object-oriented

Copyright and Disclaimer

@ Copyright 2015 by Tutorials Point (I) Pvt. Ltd.

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

precisely as possible,however,the contents may contain inaccuracies or errors.

timelinessor completenessofourwebsite oritscontentsincluding thistutorial.If

contact@tutorialspoint.com


Table of Contents

About the Tutorial .

Audience....

Prerequisites...

Copyright and Disclaimer

Table of Contents
-

PART 1: JAVASCRIPT BASICS

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?...

2.J JAVASCRIPT - Syntax .

5
Your First JavaScript Code

Whitespace and Line Breaks.

Semicolons are Optional..

Case Sensitivity...
.
Comments in JavaScript ... 19
0

9 1
3. JAVASCRIPT - Enabling 0

JavaScript in Internet Explorer 1


0
JavaScript in Firefox...

JavaScript in Chrome

JavaScript in Opera ..

Warning for Non-JavaScript Browsers.

4.JAVASCRIPT-Placement.. .12

JavaScript in <head>...</head> Section. 12

13

JavaScript in <body> and <head> Sections.. 13

JavaScript in External File... .14


Logical
Operators.
5.
JAVASCRIPT-Variables..

JavaScript Datatypes.

JavaScript Variables...

JavaScript Variable Scope...


>tutor
JavaScript Variable Names ialspo
JavaScript Reserved Words
int

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

Assignment Operators... .31

Miscellaneous Operators... 34

JAVASCRIPT - If-EIse .38

Flow Chart of if-else. 38

if Statement. 39

if...else Statement .40

if...else if... Statement 41

8. JAVASCRIPT - Switch-Case . 43

Flow Chart 43

JAVASCRIPT - While Loop .47

The while Loop .47

The do...while Loop .. ..49

10. JAVASCRIPT- For Loop ... .52

The for Loop 52

11. JAVASCRIPT-For-in Loop .55

12. JAVASCRIPT -Loop Control. .57

The break Statement... .57

The continue Statement . .59

Using Labels to Control the Flow. .60

13. JAVASCRIPT-Functions. .64

Function Definition.. .64

Calling a Function .65

Function Parameters .66

The return Statement . .67

Nested Functions... .68

Function () Constructor .70

Function Literals .71

14. JAVASCRIPT-Events. .74

What is an Event? .74

onclick Event Type 74

onsubmit Event Type. .75

onmouseoverandonmouseout. .76

HTML 5 Standard Events .77

15. JAVASCRIPT-Cookies... .82

What are Cookies?. .82

How It Works? .82

Storing Cookies.. .83

Reading Cookies . .84

Setting Cookies Expiry Date... .86

Deleting a Cookie. .87

ili

>tutorialspoint
16. JAVASCRIPT -Page Redirect .89

What is Page Redirection? .89

JavaScript Page Refresh. .89

Auto Refresh .89

How Page Re-direction Works? .90

17. JAVASCRIPT - Dialog Box... .94

Alert Dialog Box... .94

Confirmation Dialog Box.. .95

Prompt Dialog Box. .96

18. JAVASCRIPT -Void Keyword .98

19. JAVASCRIPT - Page Printing .. .101

How to Print a Page? .102

PART 2: JAVASCRIPT OBJECTS 103

20. JAVASCRIPT - Objects ..105

Object Properties. ...105

Object Methods.. ...105

User-Defined Objects ...106

Defining Methods for an Object . ...108

The 'with' Keyword. .109

21. JAVASCRIPT-Number . .112

Number Properties.. ..112

MAX_VALUE .113

MIN_VALUE ..114

NaN. ...115

NEGATIVE INFINITY. .117

POSITIVE_INFINITY ..118

Prototype.. .119

constructor . ...121

Number Methods .121

toExponential () ..122

toFixed 0. ..124

toLocaleString () .125

toPrecision ..126

toString (). .127

valueOf () ..128

22. JAVASCRIPT -Boolean . .130

Boolean Properties ..130

constructor (. ...130

Prototype... ...131

Boolean Methods .132

toSource () ..133

toString (). .134

valueOf () .135

iv
23. JAVASCRIPT - String.. .137

String Properties.. .137

constructor ...137

Length .138

Prototype.. ...139

String Methods. ...140

charAt(). ...142

charCodeAt (). .143

contact () ...144

indexOf (). .145

lastIndexOf () ..147

localeCompare () ...148

match ()

replace (). ...150

Search ().. ...153

slice () ...154

split (). ...155

substr ().. ....156

substring (). ... 157

toLocaleLowerCase() ...158

toLocaleUppereCase () ...159

toLowerCase (. ... 160

toString (). ...161

toUpperCase () ...162

valueOf () . ...163

String HTML Wrappers ...164

anchor() ... 165

big().. ....166

blink ().. ...167

bold () ...168

fixed (). ...168

fontColor () ...169

fontsize () ....170

italics () ...171

link ().. .172

small () . ...173

strike (). ....174

sub(). .175

sup (). .176

24.. JAVASCRIPT-Arrays.. .178

Array Properties .178

constructor .179

length.. .180

Prototype.. ..181

Array Methods. .182

concat () - ..184

every (). .185

filter (). .187

forEach 0 .190

>tutorialspoint
indexOf 0 .192

join () .195

lastIndexOf 0) ...196

map () ...199

pop () ...201

push ().. ...202

reduce () .204

reduceRight0 .207

reverse () ....211

shift () ..212

slice () .213

some (). ...214

sort () ...216

splice () .217

toString (). .219

unshift () .. .220

25.JAVASCRIPT-Date .222

Date Properties.. 223

constructor . .223

Prototype... .224

Date Methods. ...226

Date().. ...229

getDate(). .229

getDay() . ..230

getFullYear() .231

getHours(). .232

getMilliseconds() .233

getMinutes () ..234

getMonth () .235

getSeconds () .236

getTime () .236

getTimezoneOffset () .237

getUTCDate () . ..238

getUTCDay (... ..239

getUTCFullYear (). .240

getUTCHours () . .241

getUTCMilliseconds (). .242

getUTCMinutes () .243

getUTCMonth (). .243

getUTCSeconds () ..244

getYear () .245

setDate () . .246

setFullYear (). ..247

setHours () ..248

setMilliseconds () .249

setMinutes () .250

setMonth (). .251

setSeconds () .252

setTime (). .254

vi

>tutorialspoint
setUTCDate 0 .254

setUTCFullYear () .255

setUTCHours () . .257

setUTCMilliseconds () .258

setUTCMinutes (). ...259

setUTC Month () . ...260

setUTCSeconds ()) .261

setYear () .262

toDateString () ...263

toGMTString (). .264

toLocaleDateString () .265

tolocaleDateString () ...266

toLocaleFormat () ...266
tolocaleString () .267

toLocaleTimeSring (). ..268

toSource () ...2.69

toString (). ....270

toTimeString (). ...71

toUTCString () .272

valeOf () . ...273

Date Static Methods ...274

Date.parse (). .274

Date.UTC () . .275

26.JAVASCRIPT -Math ..277

Math Properties .277

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

Math Methods .284

abs () .285

acos0 ..287

asin () ..288

atan () .289

atan2 () .290

ceil ) ..292

cos () .293

exp(. .295

floor() .296

log() ..297

max () .298

min () ... 300

pow() .301

random() .302

round () .304

vii

>tutorialspoint
sin .305

sqrt ) .306

tan () .307

toSource () ... 309

27. JAVASCRIPT-RegExp ..310

Brackets .310

Quantifiers.... ..311

Literal Characters... ..312

Metacharacters .313

Modifiers .. ... 313

RegExp Properties .314

constructor ..314

global.. ..315

ignoreCase . ... 316

lastIndex . .318

multiline.. ..319

source ..320

RegExp Methods .321

exec) .322

test () .323

toSource () ..324

toString (). .325

28.JAVASCRIPT -DOM .327

The Legacy DOM. .328

The W3C DOM .334

The IE 4 DOM... .338

DOM Compatibility.. .342

PART 3: JAVASCRIPT ADVANCED 344

29. JAVASCRIPT - Errors and Exceptions. ..345

Syntax Errors...... ..345

Runtime Errors .345

Logical Errors ..346

The try...catch...finally Statement .346

The throw Statement .350

The onerror( ) Method . .351

30. JAVASCRIPT -Form Validation.. .354

Basic Form Validation .. .356

Data Format Validation .357

31. JAVASCRIPT -Animation .359

Manual Animation.. .360

Automated Animation . .361

Rollover with a Mouse Event.. .362

32.JAVASCRIPT-Multimedia.. .365

vili
Checking for Plug-Ins.. 366

Controlling Multimedia .367

33. JAVASCRIPT-Debugging . ...369

Error Messages in IE .369

Error Messages in Firefox or Mozilla .370

Error Notifications .371

How to Debug a Script . .371

Useful Tips for Developers .372

34. JAVASCRIPT -Image Map .374

35. JAVASCRIPT-Browsers .377

Navigator Properties .377

Navigator Methods. .378

Browser Detection... .379

ix
Part 1: JavaScript Basics

10

>tutorialspoint
6IMP
1.JAVASCRIPT-OVERVIEW

What is JavaScript?

commonly used as a part of web pages, whose implementations allow client-side

JavaScript was first knownas LiveScript,but Netscape changedits name to

Explorer, and other web browsers.

TheECMA-262SpecificationdefinedastandardversionofthecoreJavaScript

language.

Open and cross-platform.

Client-Side JavaScript

Client-sideJavaScriptisthemostcommonformofthelanguage.Thescriptshould

be included in or referenced by an HTML document for the code to be interpreted by

the browser.

The JavaScript client-side mechanism provides many advantages over traditional CGI

entered a valid e-mail address in a form field.

11
TheJavaScriptcodeisexecutedwhentheusersubmitstheform,andonlyif all the

JavaScript canbeused to trap user-initiatedevents such as buttonclicks,link

Advantages of JavaScript

The merits of using JavaScript are:

server.

dropcomponents andsliderstogive aRichInterface toyoursitevisitors.

Limitations of JavaScript

We cannot treat JavaScript as a full-fledged programming language. It lacks the


following important features:

Client-side JavaScript does not allow the reading or writing of files. This has
been kept for security reason.

support available.

JavaScript Development Tools

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.

editing tools. Some of them are listed here:

·MicrosoftFrontPage:MicrosofthasdevelopedapopularHTMLeditor called

FrontPage. FrontPage also provides web developers with a number of

popular HTML and JavaScript editor in the professional web development

wellwithdatabases,and conformstonewstandardssuchasXHTMLandXML.

editor from Macromedia that can be used to manage personal websites

effectively.

Where is JavaScript Today?

TheECMAScriptEdition5standard willbethefirstupdate tobereleased in overfour

years.JavaScript 2.0 conforms to Edition 5 of the ECMAScript standard, and the

ThespecificationforJavaScript2.0canbefoundonthefollowingsite:

http://www.ecmascript.org/

Today,Netscape'sJavaScript and Microsoft'sJScriptconformtotheECMAScript

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>

XHTML,its successor)havephased out the use of this attribute.

Type: This attribute is what is now recommended to indicate the scripting

JavaScript code

</script>

Your First JavaScript Code

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>

<!--

document.write ("Hello World!")

//-->

</script>

</body>

</htm1>

This code will produce the following result:

Hello World!

Whitespace and Line Breaks

formatand indentyourprogramsinaneatandconsistentwaythatmakesthecode

easy to read and understand.

Semicolons are Optional

as they are in C,C++,and Java.JavaScript, however,allows you to omit this

semicolonifeachofyourstatementsareplacedonaseparateline.Forexample,the

following code could be written without semicolons.

15

>tutorialspoint
<!-
-
var1 = 10

var2 = 20

//--
>

</script>

<!--

var1 = 10; var2 = 20;

//--
>

</script>

Case Sensitivity

variables, function names, and any other identifiers must always be typed with a
consistentcapitalizationofletters.

NOTE:Care should be taken whilewritingvariable andfunction namesinJavaScript.

Comments in JavaScript

ignored by JavaScript.

span multiple lines.

16
The HTML comment closing sequence --> is not recognized by JavaScript so it
should be written as //-->.

Example

ThefollowingexampleshowshowtousecommentsinJavaScript.

<!--

// This is a comment. It is similar to comments in C++

/*

* This is a multiline comment in JavaScript

* It is very similar to comments in C Programming

*/

//-->

</script>

17

>tutorialspoint
3.JAVASCRIPT-ENABLING

All the modern browsers come with built-in support for JavaScript. Frequently, you

JavaScript in Internet Explorer

. Follow Tools -> Internet Options from the menu.

- - Select Security tab from the dialog box.

- Click the Custom Level button.

Scroll down till you find the Scripting option.

. Finally click OK and come out.

To disable JavaScript support in your Internet Explorer, you need to select Disable

JavaScript in Firefox

Here are the steps to turn on or turn off JavaScript in Firefox:

'

on the value of that option -> select toggle.

18
JavaScript in Chrome

Select Settings.

JavaScript in Opera

. Follow Tools-> Preferences from the menu.

- Select Advanced option from the dialog box

. Select Content from the listed items.

Select Enable JavaScript checkbox.

Finally click OK and come out.

To disable JavaScript support in Opera, you should not select the Enable
JavaScript checkbox.

Warning for Non-JavaScript Browsers

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>

Sorry...JavaScript is needed to go ahead.

</noscript>

</body>

</htm1>

Now, if the user's browser does not support JavaScript or JavaScript is not enabled,

20

>tutorialspoint
4.JAVASCRIPT- PLACEMENT

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.

In the following section, we will see how we can place JavaScript in an HTML file in
different ways.

JavaScript in <head>...</head> Section

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>

Click here for the result

21

>tutorialspoint
</body>

</htm1>

This code will produce the following results

Click here for the result

Say Hello

JavaScript in <body>...</body> Section

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>

<p>This is web page body </p>

</body>

</htm1>

This code will produce the following results:

Hello World

22

>tutorialspoint
This is web page body

JavaScript in<body> and <head> Sections

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

HTML code using script tag and its src attribute.

<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

One of the most fundamental characteristics of a programming language is the set


of data types it supports.These are the type of values that can be represented and

. Numbers, e.g., 123, 120.50 etc.

Strings of text, e.g. "This text string" etc.

. Boolean, e.g. true or false.

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

values. All numbers in JavaScript are represented as floating-point values. JavaScript


representsnumbersusingthe64-bitfloating-pointformatdefinedbytheIEEE754
standard.

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>

You canalso declare multiplevariables withthe same varkeyword as follows:

<!--

var money, name;

//-->

</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 name = "Ali";

var money;

money = 2000.50;

I--

</script>

Note: Use the var keyword only for declaration or initialization, once for the life of

any variable name in a document.You should not re-declare samevariable twice.

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

Thescope ofavariableistheregionofyourprogram inwhichitisdefined.JavaScript

variables have only two scopes.

Global Variables:A global variable has global scopewhich means it can be

Local Variables:A local variable will bevisible only within a function where it

is defined. Function parameters are always local to that function.

Within the body of a function, a local variable takes precedence over a global variable
withthesamename.Ifyoudeclarealocalvariableorfunctionparameterwiththe

samenameasaglobalvariable,youeffectivelyhidetheglobalvariable.Takealook

into the following example.

<script type="text/javascript">

<!--

var myVar = "global"; // Declare a global variable

function checkscope( ) {

var myVar = "local"; // Declare a local variable

document.write(myVar);

//-->

</script>

It will produce the following result:

Local

JavaScript Variable Names

27

>tutorialspoint
You should not use any of the JavaScript reserved keywords as a variable

name.Thesekeywords arementioned in thenextsection.Forexample,break


or boolean variable names are not valid.

JavaScriptvariable names should not start witha numeral(0-9).Theymust

begin with a letter or an underscore character. For example, 123test is an

invalid variable name but _123test is a valid one.

JavaScriptvariable names are case-sensitive.For example,Name and name

are two different variables.

JavaScript Reserved Words

A list of all the reserved words in JavaScript are given in the following table. They
cannotbeusedasJavaScriptvariables,functions,methods,looplabels,oranyobject

names.

abstract else Instanceof switch

boolean enum int synchronized

break 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

28

>tutorialspoint
6.JAVASCRIPT - OPERATORS

What is an Operator?

Let us take a simple expression 4 + 5 is equal to 9.Here 4 and 5 are called

operators.

Arithmetic Operators

Comparison Operators

Logical (or Relational) Operators

Assignment Operators

Conditional (or ternary) Operators

Let's have a look at all the operators one by one.

Arithmetic Operators

Assume variable A holds 10 and variable B holds 20, then:

S. No. Operator and Description

+ (Addition)

1 Adds two operands

Ex: A + B will give 30

- (Subtraction)

2 Subtractsthesecond operandfromthefirst

Ex: A - B will give -10

29

>tutorialspoint
* (Multiplication)

3 Multiply both operands

Ex: A * B will give 200

/ (Division)

4 Divide the numerator by the denominator

Ex: B/ A will give 2

% (Modulus)

5 Outputs the remainder of an integer division

Ex: B % A will give 0

++ (Increment)

6 Increases an integer value by one

Ex: A++ will give 11

-- (Decrement)


Decreases an integer value by one

Ex: A-- will give 9

Note:Addition operator(+)works for Numeric as well as Strings.e.g."a"+ 10 wil

give "a10".

Example

<htm1>

<body>

<script type="text/javascript">

<!--

var a = 33;

30

>tutorialspoint
var b = 10;

var c = "Test";

var linebreak = "<br />";

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

Set the variables to different values and then try..

32

>tutorialspoint
Comparison Operators

AssumevariableAholds10andvariableBholds20,then:

S.No Operator and Description

== (Equal)

1
the condition becomes true.

Ex: (A == B) is not 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.

> (Greater than)

Checksifthevalueoftheleftoperandisgreaterthanthevalueof
3

Ex: (A > B) is not true.

< (Less than)

Checks if thevalueoftheleftoperandisless than thevalueof the


4

Ex: (A < B) is true.

>= (Greater than or Equal to)

true.

Ex: (A >= B) is not true

33

>tutorialspoint
<= (Less than or Equal to)

Checksifthevalueoftheleftoperandislessthanorequaltothe
6
value of theright operand,ifyes,then the conditionbecomes true.

Ex: (A <= B) is true.

Example

<htm1>

<body
>

<script type="text/javascript">

<!--

var a = 10;

var b = 20;

var linebreak = "<br />";

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);

34

>tutorialspoint
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);

//-->

</script>

<p>Setthevariablestodifferentvaluesanddifferentoperators andthen

try...</p>

</body>

</htm1>

Output

(a == b) => false

(a < b) => true

(a ,b)-) false

(a!- b) -> true

(a ノ= b)=> false

35

>tutorialspoint
(a <= b) => true

Setthe variables todifferentvalues anddifferentoperatorsandthen

try...

Logical Operators

AssumevariableAholds10 andvariableBholds20,then:

S.No Operator and Description

&& (Logical AND)

1 If both the operands are non-zero, then the condition becomes true.

Ex: (A && B) is true.

I1 (Logical OR)

2 If any ofthe two operands are non-zero,then the conditionbecomes true

Ex: (A II B) is true.

! (Logical NOT)

Reverses thelogicalstate ofits operand.If acondition is true,thenthe


3
Logical NOT operator will make it false

Ex: ! (A && B) is false.

Example

36

>tutorialspoint
<htm1>

<body>

<script type="text/javascript">

<!--

var a = true;

var b = false;

var linebreak = "<br />";

document.write("(a && b) => ");

result = (a && b);

document.write(result);

document.write(linebreak);

document.write("(a Il b) => ");

result = (a Il b);

document.write(result);

document.write(linebreak);

document.write("!(a && b) => ");

result = (!(a && b));

document.write(result);

document.write(linebreak) ;

//-->

</script>

37

>tutorialspoint
<p>Setthevariablestodifferentvaluesanddifferentoperators andthen

try...</p>

</body>

</htm1>

Output

(a && b) => false

(a II b)- true
!(a && b) => true

Setthevariables to differentvalues anddifferent operators andthen

try...

Bitwise Operators

JavaScriptsupports thefollowingbitwise operators:

AssumevariableAholds2andvariableBholds3,then:

S.No Operator and Description

& (Bitwise AND)

1 It performs a Boolean AND operation on each bit of its integer arguments.

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)

Ex: (B) is -4.

<< (Left Shift)

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.

>> (Right Shift)

6
number of bits specified by the right operand.

Ex: (A >> 1) is 1.

>>> (Right shift with Zero)

7
on the left are always zero.

Ex: (A >>> 1) is 1.

Example

Try the following code to implement Bitwise operator in JavaScript

<htm1>

<body>

<script type="text/javascript">

39

>tutorialspoint
<!--

var a = 2; // Bit presentation 10

var b = 3; // Bit presentation 11

var linebreak = "<br />";

document.write("(a & b) => ");

result = (a & b);

document.write(result);

document.write(linebreak);

document.write("(a I b) => ");

result = (a I b);

document.write(result);

document.write(linebreak);

document.write("(a b) => ");

result = (a b);

document.write(result);

document.write(linebreak);

document.write("(b) => ");

result = (b);
document.write(result);

document.write(linebreak);

document.write("(a << b) => ")

result = (a << b);

document.write(result);

document.write(linebreak);

40

>tutorialspoint
document.write("(a >> b) => ");

result = (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)ミ û

Setthe variables todifferentvalues anddifferentoperatorsand then

try...

Assignment Operators

S.No Operator and Description

- (Simple Assignment )
1

41

>tutorialspoint
Ex: C = A + B will assign the value of A + B into C

+= (Add and Assignment)

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

-= (Subtract and Assignment)

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

*= (Multiply and Assignment)

4
to the left operand.

Ex: C *= A is equivalent to C = C * A

/= (Divide and Assignment)

5
the left operand.

Ex: C /= A is equivalent to C = C / A

%= (Modules and Assignment)

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;

var linebreak = "<br />";

document.write("Value of a =>(a = b) => ");

result = (a = b);

document.write(result);

document.write(linebreak);

document.write("Value of a => (a += b) => ");

result = (a += b);

document.write(result);

document.write(linebreak);

document.write("Value of a => (a -= b) => ");

result = (a -= b);

document.write(result);

document.write(linebreak);

document.write("Value of a =>(a *=b)=>");

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);

document.write("Value of a =>(a %= b)=>");

result = (a %= b);

document.write(result);

document.write(linebreak);

//-->

</script>

<p>Setthevariablestodifferentvaluesanddifferentoperators andthen

try...</p>

</body>

</htm1>

Output

Value of a => (a = b) => 10

Value of a => (a += b) => 20


Value of a => (a -= b) => 10

Value of a => (a *= b) => 100

Value of a => (a /= b) => 10

Value of a => (a %= b) => 0

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.

S.No Operator and Description

? : (Conditional )
1

If Condition is true? Then value X : Otherwise value Y

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;

var linebreak = "<br />";

document.write("((a >b)?100 :200)=>");

result = (a > b) ? 100 : 200;

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

((a > b) ? 100 : 200) => 200

((a < b) ? 100 : 200) => 100

Setthevariables to differentvalues anddifferent operators andthen

try...

typeof Operator

The typeof operator is a unary operator that is placed before its single operand,
whichcanbeof anytype.Itsvalueis astringindicating thedatatype ofthe operand

The typeofoperator 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.

String Returned by typeof

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";

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);

47

>tutorialspoint
6IM P
//-->

</script>

<p>Set the variables to different values and different operators and then

try...</p>

</body>

</htm1>

Output

Result => B is String


Result => A is Numeric

Setthevariablestodifferentvaluesanddifferentoperatorsandthen

try...

48

>tutorialspoint
End of ebook preview

If you liked what you saw..

49

>tutorialspoint
6IMP

You might also like