0% found this document useful (0 votes)
5 views53 pages

JavaScript Notes 1

Uploaded by

roygichini
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views53 pages

JavaScript Notes 1

Uploaded by

roygichini
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 53

Java script notes

Introduction

JavaScript (JS) is a web programming language used with HTML and CSS.

 HTML to define the content of web pages


 CSS to specify the layout of web pages
 JavaScript to program the behavior of web pages

 JavaScript is an Object-oriented Computer Programming Language.


 It is an Interpreted programming or script language from Netscape.
 The scripting languages are easier and faster to code.
 Its first appearance was in Netscape 2.0 in 1995 with the name
'LiveScript'.

Features of JavaScript

 JavaScript is an open source scripting language.


 It is lightweight.
 It creates network-centric applications.
 It is platform independent.
 It validates form data.
 It reduces server load.

Advantages of JavaScript

 JavaScript saves server traffic.


 It performs the operations very fast.
 It is simple to learn and implement.
 It is versatile.
 JavaScript pages are executed on the client side.
 JavaScript extends its functionality to the web pages.

Disadvantages of JavaScript

 JavaScript cannot be used for networking applications.


 It doesn't have any multithreading or multiprocessor capabilities.

1
 It has security issues being a client-side scripting language.

JavaScript Functions and Events


A JavaScript function is a block of JavaScript code, that can be executed when "called" for.

For example, a function can be called when an event occurs, like when the user clicks a button.

Java script execution

There are three ways of executing JavaScript on a web


browser.

1. Inside <HEAD> tag


2. Within <BODY> tag
3. In an External File

1. Inside <HEAD> tag

Example : Simple JavaScript Program using


<HEAD> tag

head.html //File Name

<html>
<head>
<script type = "text/javascript">
function abc()
{
document.write("CareerRide Info");
}
</script>
</head>
<body>
Click the button
<input type=button onclick="abc()" value="Click">
</body>
</html>

2
Output:

CareerRide Info

Example 2
<!DOCTYPE html>
<html><head>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
<body>

<h1>A Web Page</h1>


<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>

</body>
</html>

output

2. Within <BODY> tag

Example : Simple JavaScript Program using


<BODY> tag

body.html //File Name

<html>
<body>
<script type="text/javascript">
document.write("CareerRide Info");
</script>
</body>
</html>

3
Output:
CareerRide Info

Example 2

<!DOCTYPE html>
<html>
<body>

<h1>A Web Page</h1>


<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try
it</button>

<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph
changed.";
}
</script>

</body>
</html>

3. External File
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph
changed.";
}

External scripts are practical when the same code is used in many
different web pages. JavaScript files have the file extension .js.

To use an external script, put the name of the script file in


the src (source) attribute of a <script> tag:

Scripts can also be placed in external files:

Example : Simple JavaScript Program using


External File

external.html //File Name

4
<html>
<body>
<script type="text/javascript" src="abc.js">
</script>
</body>
</html>

abc.js //External File Name


document.write("CareerRide Info");

Output:
CareerRide Info

<!DOCTYPE html>

<html>

<body>

<h2>External JavaScript</h2>

<p id="demo">A Paragraph.</p>

<button type="button" onclick="myFunction()">Try it</button>

<p>(myFunction is stored in an external file called


"myScript.js")</p>

<script src="myScript.js"></script>

</body>

</html>

output

5
External JavaScript Advantages
Placing scripts in external files has some advantages:

 It separates HTML and code


 It makes HTML and JavaScript easier to read and maintain
 Cached JavaScript files can speed up page loads

Rules for writing the JavaScript code

 Script should be placed inside the <script> tag.


 A semicolon at the end of each statement is optional.
 The single line comment is just two slashes (//) and multiple line
comment starts with /* and ends with */.
 Use 'document.write' for writing a string into HTML document.
 JavaScript is case sensitive.
 You can insert special characters with backslash (\& or \$).

JAVA SCRIPT OPERATORS

Arithmetic Operators

Operator Description

+ Addition

- Subtraction

* Multiplication

/ Division

% Modulus (Reminder)

++ Increment

-- Decrement

Comparison Operators

6
Operator Description

== Equal To

=== Exactly Equal To

!= Not Equal To

< Less Than

> Greater Than

<= Less Than or Equal To

>= Greater Than or Equal To

Assignment Operators

Operator Description

= Simple Assignment

+= Add and Assignment

-= Subtract and Assignment

*= Multiply and Assignment

/= Divide and Assignment

%= Modulus and Assignment

Logical Operators

Operator Description

&& Logical AND

|| Logical OR

! Logical NOT

Bitwise Operators

Operator Description

& Bitwise AND

| Bitwise OR

^ Bitwise XOR

˜ Bitwise NOT

7
<< Left Shift

>> Right Shift

>>> Right Shift with Zero

Special Operators

Operator Description

NEW Creates an instance of an object type.

DELETE Deletes property of an object.

DOT(.) Specifies the property or method.

VOID Does not return any value. Used to return a URL with no value.

What is a script?

Script is a small, embedded program.


 The most popular scripting languages on the web are, JavaScript or
VBScript.
 HTML does not have scripting capability, you need to use <script> tag.
 The <script> tag is used to generate a script.
 The </script> tag indicates the end of the script or program.

Example : Type attribute

<script type = “text/javascript”>


document.write(“TutorialRide”);
</script>

The 'type' attribute indicates which script language you are using with the
type attribute.

Example : Language attribute

8
<script language= “javascript”>
document.write(“TutorialRide”);
</script>

You can also specify the <script language> using the 'language' attribute.

JavaScript Variables

 JavaScript uses variables which can be thought of as Named


Containers.
 Variables are declared with the 'var' keyword.

Example:
var a;
var b;

 Variable names are case sensitive.


 You can declare multiple variables with the same 'var' keyword.

Example: var a, b;

Variable initialization

Example : Variable initialization

var a = 10;
var b = 20;

Variable Scope

1. Global Variable
 Declaring a variable outside the function makes it a Global Variable.
 Variable is accessed everywhere in the document.

Example : Simple Program on Global Variable

<html>
<head>
<script type = "text/javascript">

9
count = 5; //Global variable
var a = 4; //Global variable
function funccount() // Function Declaration
{
count+=5; // Local variable
a+=4;
document.write("<b>Inside function Global Count:
</b>"+count+"<br>");
document.write("<b>Inside function Global A: </b>"+a+"<br>");
}
</script>
</head>
<body>
<script type="text/javascript">
document.write("<b>Outside function Global Count:
</b>"+count+"<br>");
document.write("<b>Outside function Global A: </b>"+a+"<br>");
funccount();
</script>
</body>
</html>

Output:

Outside function Global Count: 5


Outside function Global A: 4
Inside function Global Count: 10
Inside function Global A: 8

2. Local Variable
 A variable declared within a function is called as Local Variable.
 It can be accessed only within the function.

Example : Simple Program on Local Variable

<html>
<head>
<script type="text/javascript">

10
function funccount(a) // Function with Argument
{
var count=5; // Local variable
count+=2;
document.write("<b>Inside Count: </b>"+count+"<br>");
a+=3;
document.write("<b>Inside A: </b>"+a+"<br>");
}
</script>
</head>
<body>
<script type="text/javascript">
var a=3, count = 0;
funccount(a);
document.write("<b>Outside Count: </b>"+count+"<br>");
document.write("<b>Outside A: </b> "+a+"<br>");
</script>
</body>
</html>

Output:

Inside Count: 7
Inside A: 6
Outside Count: 0
Outside A: 3

JavaScript Output ❮ PreviousNext ❯

JavaScript Display Possibilities


JavaScript can "display" data in different ways:

 Writing into an HTML element, using innerHTML.


 Writing into the HTML output using document.write().
 Writing into an alert box, using window.alert().
 Writing into the browser console, using console.log().

(i) Using innerHTML

11
To access an HTML element, JavaScript can use
the document.getElementById(id) method.

The id attribute defines the HTML element. The innerHTML property


defines the HTML content:

Example
<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>


<p>My First Paragraph</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>

</body>
</html>

Output

Changing the innerHTML property of an HTML element is a common way to display data in HTML.

(ii) Using document.write()

For testing purposes, it is convenient to use document.write():

Example
<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>


<p>My first paragraph.</p>

<script>
document.write(5 + 6);
</script>

12
</body>
</html>
Try it Yourself »

Using document.write() after an HTML document is loaded,


will delete all existing HTML:
Example
<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>


<p>My first paragraph.</p>

<button type="button" onclick="document.write(5 + 6)">Try


it</button>

</body>
</html>
Try it Yourself »
The document.write() method should only be used for testing.

(iii) Using window.alert()

You can use an alert box to display data:

Example
<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>


<p>My first paragraph.</p>

<script>
window.alert(5 + 6);
</script>

</body>
</html>
Try it Yourself »

You can skip the window keyword.

In JavaScript, the window object is the global scope object, that


means that variables, properties, and methods by default belong to

13
the window object. This also means that specifying
the window keyword is optional:

Example
<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>


<p>My first paragraph.</p>

<script>
alert(5 + 6);
</script>

</body>
</html>
Try it Yourself »

(iv) Using console.log()

For debugging purposes, you can call the console.log() method in


the browser to display data.

You will learn more about debugging in a later chapter.


Example
<!DOCTYPE html>
<html>
<body>

<script>
console.log(5 + 6);
</script>

</body>
</html>
Try it Yourself »

(v) JavaScript Print

JavaScript does not have any print object or print methods.

You cannot access output devices from JavaScript.

The only exception is that you can call the window.print() method
in the browser to print the content of the current window.

Example

14
<!DOCTYPE html>
<html>
<body>

<button onclick="window.print()">Print this page</button>

</body>
</html>

Output

JavaScript Statements
❮ PreviousNext ❯

Example
var x, y, z; // Statement 1
x = 5; // Statement 2
y = 6; // Statement 3
z = x + y; // Statement 4

T ry it
Yourself »

JavaScript Programs
A computer program is a list of "instructions" to be "executed" by
a computer.

In a programming language, these programming instructions are


called statements.

A JavaScript program is a list of programming statements.

In HTML, JavaScript programs are executed by the web browser.

15
JavaScript Statements
JavaScript statements are composed of:

Values, Operators, Expressions, Keywords, and Comments.

This statement tells the browser to write "Hello Dolly." inside an


HTML element with id="demo":

Example
document.getElementById("demo").innerHTML = "Hello
Dolly.";
Try it Yourself »

Most JavaScript programs contain many JavaScript statements.

The statements are executed, one by one, in the same order as they
are written.

JavaScript programs (and JavaScript statements) are often called


JavaScript code.

Semicolons ;

Semicolons separate JavaScript statements.

Add a semicolon at the end of each executable statement:

var a, b, c; // Declare 3 variables


a = 5; // Assign the value 5 to a
b = 6; // Assign the value 6 to b
c = a + b; // Assign the sum of a and b to c

T ry it Yourself »

When separated by semicolons, multiple statements on one line are


allowed:

a = 5; b = 6; c = a + b;
Try it Yourself »
On the web, you might see examples without semicolons.
Ending statements with semicolon is not required, but highly
recommended.

16
JavaScript White Space

JavaScript ignores multiple spaces. You can add white space to your
script to make it more readable.

The following lines are equivalent:

var person = "Hege";


var person="Hege";

A good practice is to put spaces around operators ( = + - * / ):

var x = y + z;

JavaScript Line Length and Line Breaks

For best readability, programmers often like to avoid code lines


longer than 80 characters.

If a JavaScript statement does not fit on one line, the best place to
break it is after an operator:

Example
document.getElementById("demo").innerHTML =
"Hello Dolly!";
Try it Yourself »

JavaScript Code Blocks

JavaScript statements can be grouped together in code blocks,


inside curly brackets {...}.

The purpose of code blocks is to define statements to be executed


together.

One place you will find statements grouped together in blocks, is in


JavaScript functions:

Example
function myFunction() {
document.getElementById("demo1").innerHTML = "Hello
Dolly!";
document.getElementById("demo2").innerHTML = "How are
you?";
}

17
Try it Yourself »
In this tutorial we use 2 spaces of indentation for code blocks.
You will learn more about functions later in this tutorial.

JavaScript Keywords

JavaScript statements often start with a keyword to identify the


JavaScript action to be performed.

Visit our Reserved Words reference to view a full list of JavaScript


keywords.

Here is a list of some of the keywords you will learn about in this
tutorial:

Keyword Description

break Terminates a switch or a loop

continue Jumps out of a loop and starts at the top

debugger Stops the execution of JavaScript, and calls (if available) the
debugging function

do ... while Executes a block of statements, and repeats the block, while a
condition is true

for Marks a block of statements to be executed, as long as a


condition is true

function Declares a function

if ... else Marks a block of statements to be executed, depending on a


condition

18
return Exits a function

switch Marks a block of statements to be executed, depending on


different cases

try ... Implements error handling to a block of statements


catch

var Declares a variable

JavaScript Syntax

JavaScript syntax is the set of rules, how JavaScript programs are


constructed:

var x, y, z; // Declare Variables


x = 5; y = 6; // Assign Values
z = x + y; // Compute Values

JavaScript Values

The JavaScript syntax defines two types of values:

 Fixed values
 Variable values

Fixed values are called Literals.

Variable values are called Variables.

JavaScript Literals

The two most important syntax rules for fixed values are:

1. Numbers are written with or without decimals:

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Numbers</h2>

19
<p>Number can be written with or without decimals.</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 10.50;
</script>

</body>
</html>

10.50

1001
Try it Yourself »

2. Strings are text, written within double or single quotes:

"John Doe"

'John Doe'

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Strings</h2>

<p>Strings can be written with double or single


quotes.</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 'John Doe';
</script>

</body>
</html>
Try it Yourself »

20
JavaScript Variables

In a programming language, variables are used to store data


values.

JavaScript uses the var keyword to declare variables.

An equal sign is used to assign values to variables.

In this example, x is defined as a variable. Then, x is assigned


(given) the value 6:

var x;

x = 6;
Try it Yourself »

JavaScript Operators

JavaScript uses arithmetic operators ( + - * / )


to compute values:

(5 + 6) * 10

Try it Yourself »

JavaScript uses an assignment operator ( = ) to assign values to


variables:

var x, y;
x = 5;
y = 6;
Try it Yourself »

JavaScript Expressions

An expression is a combination of values, variables, and operators,


which computes to a value.

The computation is called an evaluation.

21
For example, 5 * 10 evaluates to 50:

5 * 10
Try it Yourself »

Expressions can also contain variable values:

x * 10
Try it Yourself »

The values can be of various types, such as numbers and strings.

For example, "John" + " " + "Doe", evaluates to "John Doe":

"John" + " " + "Doe"


Try it Yourself »

JavaScript Keywords

JavaScript keywords are used to identify actions to be performed.

The var keyword tells the browser to create variables:

var x, y;
x = 5 + 6;
y = x * 10;
Try it Yourself »

JavaScript Comments

Not all JavaScript statements are "executed".

Code after double slashes // or between /* and */ is treated as


a comment.

Comments are ignored, and will not be executed:

var x = 5; // I will be executed

// var x = 6; I will NOT be executed


Try it Yourself »
You will learn more about comments in a later chapter.

JavaScript Identifiers

Identifiers are names.

22
In JavaScript, identifiers are used to name variables (and keywords,
and functions, and labels).

The rules for legal names are much the same in most programming
languages.

In JavaScript, the first character must be a letter, or an underscore


(_), or a dollar sign ($).

Subsequent characters may be letters, digits, underscores, or dollar


signs.

Numbers are not allowed as the first character.


This way JavaScript can easily distinguish identifiers from numbers.

JavaScript is Case Sensitive

All JavaScript identifiers are case sensitive.

The variables lastName and lastname, are two different variables:

var lastname, lastName;


lastName = "Doe";
lastname = "Peterson";
Try it Yourself »

JavaScript does not interpret VAR or Var as the keyword var.

JavaScript and Camel Case

Historically, programmers have used different ways of joining


multiple words into one variable name:

Hyphens:

first-name, last-name, master-card, inter-city.

Hyphens are not allowed in JavaScript. They are reserved for


subtractions.

Underscore:

first_name, last_name, master_card, inter_city.

Upper Camel Case (Pascal Case):

FirstName, LastName, MasterCard, InterCity.

23
Lower Camel Case:

JavaScript programmers tend to use camel case that starts with a


lowercase letter:

firstName, lastName, masterCard, interCity.

JavaScript Character Set

JavaScript uses the Unicode character set.

Unicode covers (almost) all the characters, punctuations, and


symbols in the world.

For a closer look, please study our Complete Unico

JavaScript Comments
❮ PreviousNext ❯

JavaScript comments can be used to explain JavaScript code, and to


make it more readable.

JavaScript comments can also be used to prevent execution, when


testing alternative code.

Single Line Comments

Single line comments start with //.

Any text between // and the end of the line will be ignored by
JavaScript (will not be executed).

This example uses a single-line comment before each code line:

Example
<!DOCTYPE html>
<html>
<body>

24
<h1 id="myH"></h1>
<p id="myP"></p>

<script>
// Change heading:
document.getElementById("myH").innerHTML = "JavaScript
Comments";
// Change paragraph:
document.getElementById("myP").innerHTML = "My first
paragraph.";
</script>

</body>
</html>

This example uses a single line comment at the end of each line to
explain the code:

Example

<!DOCTYPE html>

<html>

<body>

<h2>JavaScript Comments</h2>

<p id="demo"></p>

<script>

var x = 5; // Declare x, give it the value of 5

var y = x + 2; // Declare y, give it the value of x + 2

// Write y to demo:

document.getElementById("demo").innerHTML = y;

</script>

</body>

</html>

25
Multi-line Comments

Multi-line comments start with /* and end with */.

Any text between /* and */ will be ignored by JavaScript.

This example uses a multi-line comment (a comment block) to


explain the code:

Example
/*
The code below will change
the heading with id = "myH"
and the paragraph with id = "myP"
in my web page:
*/

<!DOCTYPE html>
<html>
<body>

<h1 id="myH"></h1>
<p id="myP"></p>

<script>
/*
The code below will change
the heading with id = "myH"
and the paragraph with id = "myP"
*/
document.getElementById("myH").innerHTML = "JavaScript
Comments";
document.getElementById("myP").innerHTML = "My first
paragraph.";
</script>

</body>
</html>

26
Try it Yourself »
It is most common to use single line comments.
Block comments are often used for formal documentation.

Using Comments to Prevent Execution

Using comments to prevent execution of code is suitable for code


testing.

Adding // in front of a code line changes the code lines from an


executable line to a comment.

This example uses // to prevent execution of one of the code lines:

Example
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Comments</h2>

<h1 id="myH"></h1>

<p id="myP"></p>

<script>
//document.getElementById("myH").innerHTML = "My First
Page";
document.getElementById("myP").innerHTML = "My first
paragraph.";
</script>

<p>The line starting with // is not executed.</p>

</body>
</html>

.";

27
Try it Yourself »

This example uses a comment block to prevent execution of


multiple lines:

Example
/*
document.getElementById("myH").innerHTML = "My First
Page";
document.getElementById("myP").innerHTML = "My first
paragraph.";
*/
Try it Yourself »
JavaScript Variables
❮ PreviousNext ❯

JavaScript variables are containers for storing data values.

In this example, x, y, and z, are variables, declared with


the var keyword:

Example
var x = 5;
var y = 6;
var z = x + y;
Try it Yourself »

From the example above, you can expect:

 x stores the value 5


 y stores the value 6
 z stores the value 11

JavaScript Identifiers

All JavaScript variables must be identified with unique names.

These unique names are called identifiers.

Identifiers can be short names (like x and y) or more descriptive


names (age, sum, totalVolume).

The general rules for constructing names for variables (unique


identifiers) are:

28
 Names can contain letters, digits, underscores, and dollar
signs.
 Names must begin with a letter
 Names can also begin with $ and _ (but we will not use it in
this tutorial)
 Names are case sensitive (y and Y are different variables)
 Reserved words (like JavaScript keywords) cannot be used as
names

JavaScript identifiers are case-sensitive.

The Assignment Operator

In JavaScript, the equal sign (=) is an "assignment" operator, not an


"equal to" operator.

This is different from algebra. The following does not make sense in
algebra:

x = x + 5

In JavaScript, however, it makes perfect sense: it assigns the value


of x + 5 to x.

(It calculates the value of x + 5 and puts the result into x. The value
of x is incremented by 5.)

The "equal to" operator is written like == in JavaScript.

JavaScript Data Types

JavaScript variables can hold numbers like 100 and text values like
"John Doe".

In programming, text values are called text strings.

JavaScript can handle many types of data, but for now, just think of
numbers and strings.

Strings are written inside double or single quotes. Numbers are


written without quotes.

If you put a number in quotes, it will be treated as a text string.

Example
var pi = 3.14;
var person = "John Doe";
var answer = 'Yes I am!';

29
Try it Yourself »

Declaring (Creating) JavaScript Variables

Creating a variable in JavaScript is called "declaring" a variable.

You declare a JavaScript variable with the var keyword:

var carName;

After the declaration, the variable has no value (technically it has


the value of undefined).

To assign a value to the variable, use the equal sign:

carName = "Volvo";

You can also assign a value to the variable when you declare it:

var carName = "Volvo";

In the example below, we create a variable called carName and


assign the value "Volvo" to it.

Then we "output" the value inside an HTML paragraph with


id="demo":

Example
<p id="demo"></p>

<script>
var carName = "Volvo";
document.getElementById("demo").innerHTML = carName;
</script>
Try it Yourself »
It's a good programming practice to declare all variables at the
beginning of a script.

One Statement, Many Variables

You can declare many variables in one statement.

Start the statement with var and separate the variables by comma:

var person = "John Doe", carName = "Volvo", price = 200;


Try it Yourself »

A declaration can span multiple lines:

30
var person = "John Doe",
carName = "Volvo",
price = 200;
Try it Yourself »

Value = undefined

In computer programs, variables are often declared without a value.


The value can be something that has to be calculated, or something
that will be provided later, like user input.

A variable declared without a value will have the value undefined.

The variable carName will have the value undefined after the
execution of this statement:

Example
var carName;
Try it Yourself »

Re-Declaring JavaScript Variables

If you re-declare a JavaScript variable, it will not lose its value.

The variable carName will still have the value "Volvo" after the
execution of these statements:

Example
var carName = "Volvo";
var carName;
Try it Yourself »

JavaScript Arithmetic

As with algebra, you can do arithmetic with JavaScript variables,


using operators like = and +:

Example
var x = 5 + 2 + 3;

Try it Yourself »

You can also add strings, but strings will be concatenated:

Example
var x = "John" + " " + "Doe";
Try it Yourself »

31
Also try this:

Example
var x = "5" + 2 + 3;

Try it Yourself »
If you put a number in quotes, the rest of the numbers will be
treated as strings, and concatenated.

Now try this:

Example
var x = 2 + 3 + "5";

Try it Yourself »

JavaScript Dollar Sign $

Remember that JavaScript identifiers (names) must begin with:

 A letter (A-Z or a-z)


 A dollar sign ($)
 Or an underscore (_)

Since JavaScript treats a dollar sign as a letter, identifiers containing


$ are valid variable names:

Example
var $$$ = "Hello World";
var $ = 2;
var $myMoney = 5;

Try it Yourself »

Using the dollar sign is not very common in JavaScript, but


professional programmers often use it as an alias for the main
function in a JavaScript library.

In the JavaScript library jQuery, for instance, the main function $ is


used to select HTML elements. In jQuery $("p"); means "select all
p elements".

JavaScript Underscore (_)

Since JavaScript treats underscore as a letter, identifiers containing


_ are valid variable names:

32
Example
var _lastName = "Johnson";
var _x = 2;
var _100 = 5;

Try it Yourself »

Using the underscore is not very common in JavaScript, but a


convention among professional programmers is to use it as an alias
for "private (hidden)" variables.

Test Yourself With Exercises


Exercise:

Create a variable called carName and assign the value Volvo to it.

var = " ";

Submit Answer »

Start the Exercise

JavaScript Operators
❮ PreviousNext ❯

Example

Assign values to variables and add them together:

var x = 5; // assign the value 5 to x


var y = 2; // assign the value 2 to y
var z = x + y; // assign the value 7 to z (5 + 2)
Try it Yourself »

The assignment operator (=) assigns a value to a variable.

Assignment
var x = 10;
Try it Yourself »

The addition operator (+) adds numbers:

Adding
var x = 5;
var y = 2;
var z = x + y;

33
Try it Yourself »

The multiplication operator (*) multiplies numbers.

Multiplying

var x = 5;
var y = 2;
var z = x * y;

Javascript controls and looping

1. If Statement

IF statement is a conditional branching statement. In 'IF'


statement, if the condition is true a group of statement is executed.
And if the condition is false, the following statement is skipped.
Syntax : If statement

if(condition)
{
//Statement 1;
//Statement 2;
}

Example : Simple Program for IF Statement

<html>
<body>
<script type="text/javascript">

34
var num = prompt("Enter Number");
if (num > 0)
{
alert("Given number is Positive!!!");
}
</script>
</body>
</html>

Output:

2. If – Else Statement

 If – Else is a two-way decision statement.


 It is used to make decisions and execute statements conditionally.
Flow Diagram of If – Else Statement

Syntax : If-Else statement

if (condition)
{
//Statement 1;
}
else if(condition)
{
//Statement 2;
}
else
{
//Statement 3;
}

Example : Simple Program for If-Else Statement

35
<html>
<head>
<script type="text/javascript">
var no = prompt("Enter a Number to find Odd or Even");
no = parseInt(no);
if (isNaN(no))
{
alert("Please Enter a Number");
}
else if (no == 0)
{
alert("The Number is Zero");
}
else if (no % 2)
{
alert("The Number is Odd");
}
else
{
alert("The Number is Even");
}
</script>
</head>
</html>

Output:

36
37
3. Switch Statement

 Switch is used to perform different actions on different conditions.


 It is used to compare the same expression to several different
values.
Flow Diagram of Switch Statement

Syntax

38
switch(expression)
{
case condition 1:
//Statements;
break;
case condition 2:
//Statements;
break;
case condition 3:
//Statements;
break;
.
.
case condition n:
//Statements;
break;
default:
//Statement;
}

Example : Simple Program for Switch Statement

<html>
<head>
<script type="text/javascript">
var day = prompt("Enter a number between 1 and 7");
switch (day)
{
case (day="1"):
document.write("Sunday");
break;
case (day="2"):
document.write("Monday");
break;
case (day="3"):

39
document.write("Tuesday");
break;
case (day="4"):
document.write("Wednesday");
break;
case (day="5"):
document.write("Thursday");
break;
case (day="6"):
document.write("Friday");
break;
case (day="7"):
document.write("Saturday");
break;
default:
document.write("Invalid Weekday");
break;
}
</script>
</head>
</html>

Output:

40
4. For Loop
 For loop is a compact form of looping.

It includes three important parts:


1. Loop Initialization
2. Test Condition
3. Iteration

 All these three parts come in a single line separated by


semicolons(;).

41
Flow Diagram of 'For' Loop

Syntax

for(initialization; test-condition; increment/decrement)


{
//Statements;
}

Example : Palindrome Program using For Loop

<html>
<body>
<script type="text/javascript">
function palindrome()
{
var revstr = " ";
var strr = document.getElementById("strr").value;
var i = strr.length;

42
for(var j=i; j>=0; j--)
{
revstr = revstr+strr.charAt(j);
}
if(strr == revstr)
{
alert(strr+" - is Palindrome");
}
else
{
alert(strr+" - is not a Palindrome");
}
}
</script>
<form>
Enter a String or Number: <input type="text" id="strr"
name="checkpalindrome"><br>
<input type="submit" value="Check"
onclick="palindrome();">
</form>
</body>
</html>

Output:

43
5. For-in Loop

 For-in loop is used to traverse all the properties of an object.


 It is designed for looping through arrays.
Syntax

for (variable_name in Object)


{
//Statements;
}

6. While Loop

 While loop is an entry-controlled loop statement.


 It is the most basic loop in JavaScript.
 It executes a statement repeatedly as long as expression is true.
 Once the expression becomes false, the loop terminates.
Flow Diagram of While Loop

Syntax

while (condition)
{
//Statements;
}

44
Example : Fibonacci Series Program using While Loop

<html>
<body>
<script type="text/javascript">
var no1=0,no2=1,no3=0;
document.write("Fibonacci Series:"+"<br>");
while (no2<=10)
{
no3 = no1+no2;
no1 = no2;
no2 = no3;
document.write(no3+"<br>");
}
</script>
</body>
</html>

Output:

7. Do-While Loop

 Do-While loop is an exit-controlled loop statement.


 Similar to the While loop, the only difference is condition will be
checked at the end of the loop.
 The loop is executed at least once, even if the condition is false.

45
Flow Diagram of Do – While

Syntax

do
{
//Statements;
}
while(condition);

Example : Simple Program on Do-While Loop

<html>
<body>
<script type ="text/javascript">
var i = 0;
do
{
document.write(i+"<br>")
i++;
}
while (i <= 5)

46
</script>
</body>
</html>

Output:
0
1
2
3
4
5

Difference between While Loop and Do – While Loop

While Loop Do – While Loop


In while loop, first it checks the condition and In Do – While loop, first it executes
then executes the program. and then checks the condition.
It is an entry – controlled loop. It is an exit – controlled loop.
The condition will come before the body. The condition will come after the bo
If the condition is false, then it terminates the It runs at least once, even though th
loop. is false.
It is a counter-controlled loop. It is a iterative control loop.

8. Break Statement

 Break statement is used to jump out of a loop.


 It is used to exit a loop early, breaking out of the enclosing curly
braces.
Syntax:
break;

47
Flow Diagram of Break Statement

9. Continue Statement

 Continue statement causes the loop to continue with the next


iteration.
 It skips the remaining code block.

Introduction to Event Handling

 Event Handling is a software routine that processes actions, such as


keystrokes and mouse movements.
 It is the receipt of an event at some event handler from an event producer
and subsequent processes.

Functions of Event Handling

 Event Handling identifies where an event should be forwarded.


 It makes the forward event.
 It receives the forwarded event.

48
 It takes some kind of appropriate action in response, such as writing to a
log, sending an error or recovery routine or sending a message.
 The event handler may ultimately forward the event to an event
consumer.
Event Handler Description

onAbort It executes when the user aborts loading an image.

onBlur It executes when the input focus leaves the field of a text, textarea or a select option.

onChange It executes when the input focus exits the field after the user modifies its text.

onClick In this, a function is called when an object in a button is clicked, a link is pushed, a check
an image map is selected. It can return false to cancel the action.

onError It executes when an error occurs while loading a document or an image.

onFocus It executes when input focus enters the field by tabbing in or by clicking but not selecting
field.

onLoad It executes when a window or image finishes loading.

onMouseOver The JavaScript code is called when the mouse is placed over a specific link or an object.

onMouseOut The JavaScript code is called when the mouse leaves a specific link or an object.

onReset It executes when the user resets a form by clicking on the reset button.

onSelect It executes when the user selects some of the text within a text or textarea field.

onSubmit It calls when the form is submitted.

onUnload It calls when a document is exited.

Event Handlers

Example : Simple Program on onload() Event handler

<html>
<head>
<script type="text/javascript">
function time()
{
var d = new Date();
var ty = d.getHours() + ":"+d.getMinutes()+":"+d.getSeconds();
document.frmty.timetxt.value=ty;

49
setInterval("time()",1000)
}
</script>
</head>
<body onload="time()">
<center><h2>Displaying Time</h2>
<form name="frmty">
<input type=text name=timetxt size="8">
</form>
</center>
</body>
</html>

Output:

Example: Simple Program on onsubmit() &


onfocus() Event handler

<html>
<body>
<script>
function validateform()
{
var uname=document.myform.name.value;
var upassword=document.myform.password.value;
if (uname==null || uname=="")
{
alert("Name cannot be left blank");
return false;
}
else if(upassword.length<6)
{

50
alert("Password must be at least 6 characters long.");
return false;
}
}
function emailvalidation()
{
var a=document.myform.email.value
if (a.indexOf("@")==-1)
{
alert("Please enter valid email address")
document.myform.email.focus()
}
}
</script>
<body>
<form name="myform" method="post" action="validpage.html"
onsubmit="return validateform()">
Email: <input type="text" size="20" name="email"
onblur="emailvalidation()"><br>
User Name: <input type="text" name="name"><br>
Password: <input type="password" name="password"><br>
<input type="submit" value="Submit" >
</form>
</body>
</html>

validpage.html //File name

<html>
<body>
<script type="text/javascript">
alert("You are a Valid User !!!");
</script>
</body>
</html>

51
Output:

52
Flow Diagram of Continue Statement

53

You might also like