Javascript Notes - Web App - Xii-1
Javascript Notes - Web App - Xii-1
Client-Side JavaScript (CSJS) -- an extended version of JavaScript that enables the enhancement and
manipulation of web pages and client browsers.
Server-Side JavaScript (SSJS) -- an extended version of JavaScript that enables back-end access to
databases, file systems, and servers.
What is JavaScript?
● JavaScript was designed to add interactivity to HTML pages
● JavaScript is a case sensitive scripting language for web pages.
● A scripting language is a lightweight programming language
● JavaScript is usually embedded directly into HTML pages
● JavaScript is an interpreted language (means that scripts execute without preliminary
compilation)
● Everyone can use JavaScript without purchasing a license .
Executing JavaScript
● Load into browser (need HTML document)
● Browser detects syntax and run-time errors
Syntax:
<script>
// JavaScript Code
</script>
<html> <html>
<body> <head>
<h1>My First Web Page</h1> </head>
<p>My first paragraph.</p> <body >
<script type="text/javascript"> <script type="text/javascript">
document.write(5 + 6); document.write("This is the web page");
</script> alert("This is an alert box .Click to close");
</body> </script>
</html> </body>
</html>
● Embedded scripts
Embed JavaScript code in an XHTML document—either in the head or in the body.
<script type=“text/javascript”>
x=3; y=9;
document.writeln( x + y );
</script>
● Inline Code
Add dynamic functionality to an individual element
<img onMouseOver=“doThisFunction(this)”>
<html>
<head>
<title> Incorporating Javascript</title>
<script type="text/javascript" src="hello.js"> </script># external js
<script type="text/javascript"> # internal js
<!--
document.write("<h1>I'm generated by a script in the header</h1>");
//-->
</script>
</head>
<body> <!-- Document content -->
<h1> Incorporating Javascript</h1>
<script type="text/javascript">
<!--
document.write("<p>I'm generated by a script in the body</p>");
//-->
</script>
</body> </html>
document. write(String);
Its the basic JavaScript command used to display string on web page.
When browser encounter document.write(string) statement inside <script></script> tag it will display
the string on webpage. We can add HTML tags inside string to format the output of string
Example:
Putting a script in <head>
In the example, we have included two (very simple) scripts in the head region of the page. The first is
called in from an external file, the second is written within the page itself. These scripts are executed
when the page is loaded, which is why the text that they generate is the first thing to appear on the page.
The exception to this is if these scripts define functions, in which case the function is only executed
when it is called.
Scripts in <body>
Scripts that are placed in the <body> of the document are called as they are loaded in, and so any
content that they generate is placed at the point where the script is called.
INPUT/OUTPUT IN JAVASCRIPT
JavaScript is special from other languages because it can accept input and produce output on the basis of
that input in the same page.
Functions to show output:
1)window.alert( )
2)window.status( )
3)document.write( )
4)document.writeln( )
window.alert(): This function show the message in a small messagebox . The messagebox contains the
string and an "OK"button on it. If the user presses the "OK" button the messagebox disappears. The
message to be displayed has to be
passed as parameter
window.alert()
Code example :
<html>
<body>
<script language="Javascript">
window.alert ("Hello");
window. alert(“bye”)
</script>
</body>
</html>
Output:
window.status():
This function show the message in statusbar . The message to be displayed has to be passed
as parameter window.status()
Code example :
<html>
<body>
<script language="Javascript">
window.status ("Welcome to JavaScript“)
</script >
</body>
window.prompt( ): This function is used to get any value from the user. This function takes two
optional parameters . Returns the value entered by the user in String format, however if user press
"cancel" returns "Null"
String= window.prompt("Question","default answer")
Code example :
<html>
<body>
<script language="Javascript">
var s; #optional statement
s = window.prompt("What is your name ?", "your name here" );# The value user inputs will be stored
in the variable s
document.write( s);
</script >
</body>
</html>
The above program asks user his name, and when the user enters his name and
press "OK", the name of user is printed.
window.confirm() :
This function prompts the user to confirm the decision. It shows a messageBox with two buttons "OK"
and "CANCEL" on it. If user press "OK" it returns "true" , if user press "CANCEL" it returns false.
<html>
<body>
<script language="Javascript">
var ans;
ans = window.confirm("Are you ready?")
document.write(ans)
if (ans==true) // check users response
document.writeln( "Start learning JavaScript");
else
document.writeln( "Try later");
</script >
</body>
</html>
document. write(String);
Basic JavaScript command used to display string on web page.When browser encounter inside
document.write(string) statement <script></script> tag it will display the string on webpage. We can
add HTML tags inside string to format the output of string
document.writeln(string)
Writes a line to the page with a carriage return at the end.Must be between <PRE> … </PRE> tags
<html> <body>
<script Language=“JavaScript”>
document.writeln("1");
document.writeln("2");
document.writeln("3");
document.writeln("4");
</script>
<script Language=“JavaScript”>
document.write("<pre>")
document.writeln("1");
document.writeln("2");
document.writeln("3");
document.writeln("4");
document.write("</pre>")
</script>
</body></html>
<form name="addressform">
Name: <input name="yourname"><br />
Phone: <input name="phone"><br />
Email: <input name="email"><br />
</form>
Syntax:
document.formname.elementname.value
<form name="alertform">
Enter your name:
<input type="text" name="yourname">
<input type="button" value= "Go"
onClick="window.alert('Hello ' + →
document.alertform.yourname.value);">
</form>
JAVASCRIPT PROGRAMMING
A program can do many things, including calculations, sorting names, preparing phone lists, displaying
images, validating forms, etc. But to do anything, the program works with the data that is given to it.
Data types specify what kind of data, such as numbers and characters, can be stored and manipulated
within a program. JavaScript supports a number of fundamental data types. These types can be broken
down into two categories:
In addition to the three core data types, there are two other special types that consist of a single value:
• null
• undefined
Numeric Literals: JavaScript supports both integers and floating-point numbers. Integers are whole
numbers and do not contain a decimal point, such as 123 and –6. Integers can be expressed in decimal
(base 10), octal (base 8), and hexadecimal (base 16), and are either positive or negative values.
Floating-point numbers are fractional numbers such as 123.56 or –2.5. They must contain a decimal
point or an exponent specifier, such as 1.3e–2. The letter “e” for expo- nent notation can be either
uppercase or lowercase. JavaScriptnumbers can be very large (e.g., 10308 or 10–308 ). 12345 integer
23.45 float .234E-2 scientific notation .234e+3 scientific notation 0x456fff hexadecimal 0x456FFF
hexadecimal 0777 octal
String Literals and Quoting: String literals are set of characters enclosed in either double or single
quotes. The quotes must be matched. If the string starts with a single quote, it must end with a matching
single quote, and likewise if it starts with a double quote, it must end with a double quote. Single quotes
can hide double quotes, and double quotes can hide single quotes:
var oldcar="Big Brown Station Wagon";
var mycomputer="Pentium 3, 500 MHz, 128MB RAM";
var oldcomputer=‘386 SX, 40 mHz, 8MB RAM’;
var jibberish="what? cool! I am @ home 4 now. (cool, right?)";
An empty set of quotes is called the null string.
Eg: “ ”
If a number is enclosed in quotes, it is considered a string; for example, “5” is a string, whereas 5
is a number.
Trying to close the string with the wrong type of quotation mark, or leaving out an opening or closing
quotation mark, will cause problems.
var mycar="Red Corvette';
var myhouse= 'small brick house";
var mycomputer="Pentium 3, 500 mHz, 128MB RAM;
These mistakes will result in an “Unterminated String” error in the Web browser. Strings are called
constants or literals. The string value “hello” is called a string constant or literal. To change a string
requires replacing it with anotherstring. Strings can contain escape sequences (a single character
preceded with a backslash).
The escape sequences will work only if in a tag or an alert dialog box.
STRING CONCATENATION
Boolean Literals:
Boolean literals are logical values that have only one of two values, true or false. You can think of the
values as yes or no, on or off, or 1 or 0. They are used to test whether a condition is true or false. When
using numeric comparison and equality operators, the value true evaluates to 1 and false evaluates to 0.
Variables:
● A variable is a name given to a memory location to store value in the computer’s main storage.
● The keyword var is used to declare variable.(optional).
● It is a name used in the program that represents data (value).
● The value assigned to the variable name may change (vary) as the program is executed.
● The program can always access the current value of the variable by referring to its name.
Variables can be declared & Initialized using the var statement and = assignment operator
SYNTAX:
var variable_name = value; // initialized var variable_name; // uninitialized variable_name;
firstname=“Vinod”
Roll=8;
Output:
How JavaScript Converts Data Types:
TYPE CASTING
It’s also possible to convert values using a process called type casting. Type casting allows you to access
a specific value as if it were of a different type. Three type casts are available in JavaScript:
Boolean(value) – casts the given value as a Boolean Number(value) – casts the given value as a number
(either integer or floating-point) String(value) – casts the given value a string
Number("42"); // returns 42
String(42); // returns "42"
Boolean(42); // returns true
Conversion Rules
JavaScript will attempt to carry out the specified conversions in the following situations: Boolean is
converted to a Number (1/0) before comparison. In a Number comparison, if an entry is NaN it will be
converted to false. Also when comparing a Number, if an Object is entered it will attempt to cast it to an
Integer. If two Objects are compared it is the memory address that is checked for comparison. The
Literals ‘null’ and ‘Undefined’ are judged to be the same entity. They will not cast to 0, “” or false. If a
String and a Number are compared, the String will be cast to an Integer. If an Object and a String are
compared, the Object will be cast to a String.
Conversion to Strings
All Primitive data types in JavaScript are included with a ‘toString()’ method which can be called
manually to convert the data type to a string. When dealing with floats, JavaScript will not maintain
decimal places that are not required.
This method also has an optional radix parameter which can be used to change the base level of the
returned number.
Numbers As there are two data types within the term of Number, Integers and Floats, there are two
functions for converting primitive data types into numbers. These are ‘parseInt()’ and ‘parseFloat()’.
‘parseInt()’ function can receive an option radix parameter ‘parseFloat()’function cannot. These methods
will convert up to the first invalid character and return the result. It is also worthy of note that any
number passed to the ‘parseInt()’ function with a leading ’0′ will be treated as an octal number, rather
than a decimal.
Number accepts parameters, that are string representations of decimal, octal or hexadecimal numbers.
Number("12"); // decimal, 12
Number("0x12"); // hexadecimal, 18
Number("012"); // octal, 10
While this is true for parseInt as well, parseInt goes further. parseInt accepts parameters that start with a
string representation of a number.
parseInt("314abc"); // 314
Number("314abc"); // NaN
Boolean Primitive data types can be converted to Boolean using JavaScript’s built in Casting method,
‘Boolean()’.
var intNumber= 1;
document.write( Boolean(intNumber) );
// outputs: true - Integer greater than 1.
OPERATORS AND EXPRESSIONS
● Operators help perform an operation over data at runtime .
● Takes one or more arguments (operands)
● Produces a new value
● Operators have Precedence-Precedence defines which will be evaluated first and Associativity
Operators in JavaScript :
Unary – take one operand
Binary – take two operands
Ternary (?:) – takes three operands
Except for the assignment operators, all binary operators are left-associative
The assignment operators and the conditional operator (?:) are right-associative.
<script language="javascript">
a=10
b=-10
c=b%3
a++
b--
document.write(a+"<br>")
document.write(b+"<br>")
document.write(c)
</script>
Statement True/False
FirstName== ‘Ryan’ True
LastName==”George” False
StudentID==”S056” False
Attendance >20 True
FirstName!= “John” True
Age<12 False
Class>=10 True
Age<=20 True
Logical Operators
Logical operators take boolean operands and return boolean result Operator ! turns true to false and false
to true Assume variable A holds 10 and variable B holds 20 then:
<html>
<head>
<title>Logical Operators</title>
</head>
<body>
<script language="javascript">
var age, height, entrancefee // optional
age= window.prompt("Enter your age:","0")
height= window.prompt("Enter your height:","0")
if (age>=12 || height>=140)// or operator
{entrancefee="$10"}
else
{entrancefee="$8"};
document.write("The entrance fee is: "+entrancefee);
</script>
</body>
Assignment Operators
Conditional operators let JavaScript program executes certain jobs according to certain conditions. The
format of the conditional operator is:
The question mark ? separates the conditional expression and execution 1 whilst the colon : separates
execution 1 and execution 2.
If the conditional expression is true, then JavaScript will run execution 1 and ignores execution2.
However, if the conditional expression is false, then JavaScript will ignore execution 1 and run
execution 2.
Therefore, the symbol ? and : completely replace If and Else.
typeof operator
The typeof 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" .
Other Operators
Member access operator . is used to access object members Square brackets [] are used with arrays
indexers and attributes Parentheses ( ) are used to override the default operator precedence The new
operator is used to create new objects This operator references the current context .
Expressions
Expressions are sequences of operators, literals and variables that are evaluated to some value
Examples:
var r = (150-20) / 2 + 5; // r=70
// Expression for calculation of circle area
var surface = Math.PI * r * r; // Expression for calculation of circle perimeter
var perimeter = 2 * Math.PI * r;
Decision making is the most important part of making any programming or scripting language
interactive. While writing a program, there may be a situation when you need to adopt one out of a given
set of paths. In such cases, you need to use conditional statements that allow your program to make
correct decisions and perform right actions.
if/if-else
In JavaScript condition or logical expression is used with if-else. if-else statement provides a way to
change program flow based on a condition. We can have if statement without else but we cannot have
else without if.
Syntax 1:
if (condition)
{
statement / block
}
Syntax 2:
if (condition)
{
statement1 / block1
}
else
{
statement2 / block2
}
Syntax 3:
if (condition)
statement1
else if (condition)
statement2
else if (condition)
statement3
.
.
.
else
statement4
a) If the condition is TRUE then the statement1 or block1 is executed and the
statement or the block after the else is ignored.
b) If the condition is FALSE then the statement or block after the condition is
ignored and the statement2 or block2 is executed.
✓Boolean variable
✓Boolean logical expression
✓Comparison expression
✓Integer, object, function... everything
<html>
<head>
</head>
<body>
<script language=“JavaScript">
mark=window.prompt("Enter mark:","0")
if(mark>=80)
document.write("Grade="+"A")
else
document.write("Grade="+“B")
</script>
</body>
Explanation of output: Inputted marks is 70, that is, variable marks has a value70.
if condition is tested (marks>=80), condition is FALSE. Therefore document.write("Grade="+“A")
is ignored and the statement after else, document.write("Grade="+“B") is executed.
<html>
<head>
<title>&& operator with if -else</title>
</head>
<body>
<script type="text/javascript">
a=window.prompt("Enter First
Angle”,"0");
b=window.prompt("Enter Second
Angle","0");
c=window.prompt("Enter Third
Angle","0");
if (a==60 && b ==60 && c ==60 )
alert(" Equiangular Triangle")
else
alert(" Not an Equiangular Triangle")
</script>
</body>
</html>
</html>
<html> <head>
<title> Using Nested if –else </title>
</head> <body>
<script type="text/javascript">
day=window.prompt("Enter Day[0-6]");
if (day == 0 )
alert ("Sunday") ;
else if (day == 1 )
{ alert ("Monday") ; }
else if (day == 2)
{ alert ("Tuesday") ; }
else if (day == 3)
{ alert ("Wednesday") ; }
else if (day == 4)
{ alert ("Thursday") ; }
else if (day == 5)
{ alert ("Friday") ; }
else if (day == 6)
{ alert ("Saturday") ; }
else { alert ("Error - invalid day.") ; }
</script>
</body> </html>
SWITCH CASE
Syntax
switch (expression )
{ case value1 :
statement(s)
break ;
case value2 :
statement(s)
break ;
...
default :
statement(s)
break ; }
expression" is used to generate a test value that will be tested against with expected values
specified in "case" clauses. The execution of a "switch case"statement goes like this:
"case" clauses are possible execution starting points. Each "case" clause will be visited
sequentially from top to bottom. If the expected value of a "case" clause equals to the
test value resulted from the switch expression, the execution starts from those statements listed in
this "case" clause. Once the execution started, it will continue until a break statement is reached
or the end of the "switch" block is reached.
The "default" clause is optional. But if it is provided, it will become the execution starting point
when all case tests before the "default" clause are failed.
Eg: Input number of month and print the name of the month
<html> <head>
</head> <body>
<script language ="JavaScript">
month= parseInt(window.prompt("Enter Month[1-12]"))
switch(month)
{
case 1: alert("January")
break;
case 2: alert("February")
break;
case 3: alert("March")
break;
case 4: alert("April")
break;
case 5: alert("May")
break;
case 6: alert("June")
break;
case 7: alert("July")
break;
case 8: alert("August")
break;
case 9: alert("September")
break;
case 10: alert("October")
break;
case 11: alert("November")
break;
case 12: alert("December")
break;
default: alert ("Error - invalid month")
}
</script>
</body>
</html>
LOOPS-ITERATION
a) Control Variable and its Initialisation: Generally a loop in JavaScript has a control
variable. Control variable is generally an integer type or character type or floating
point type. But we can have loop in JavaScriptwith out a control variable. We will
discuss such loops later. If a loop has a control variable then the control variable has
to be initialized.
Syntax
while(Condition)
{
JavaScript Statements;
Updating of control variable
before the close
}
When program execution reaches a while statement, the following events occur:
1. The (condition) is evaluated.
2. Condition is TRUE (nonzero), the Block / Statement is executed.
3. Inside the Block / Statement, control variable is updated and Condition is tested once
These three steps are repeated till Condition is FALSE.
When the condition is evaluated to be false, the loop is terminates.
The while loop is an example of entry controlled loop, since first the Condition is
tested and then the Block or the Statement is executed.
do while: Loop through a set of statements as long as a condition is true but runs at least one
before checking condition
Syntax:
do
{
JavaScript Statements;
Updating of control variable
before the close
} while(Condition);
The loop runs once before (condition) Checking (condition) may be any JavaScript valid logical
expression.
for loop - The for loop is almost similar to while loop but it is more compact than while
Loop.
The while loop has three important components:
an initialization of control variable, a terminating condition and update of control variable.
In a for loop all three components are together immediately after the keyword
for. A for loop is also an example of entry controlled loop.
Syntax:
for (Initialisation; Condition; Update)
Block / Statement;
for ( x = 1; x < 10 ; x = x + 1 )
{ document.write ( x ) ; }
For/In Loop - The JavaScript for/in statement loops through the properties of object:
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.
Example
var person = {fname:"John", lname:"Doe", age:25};
var text = "";
var x;
for (x in person)
{ text += person[x];}
document. write(“Output will be :” +text) ;