JavaScript(PART : 02)
Switch
The objective of a switch statement is to give an
expression to evaluate and several different statements to execute based on the
value of the expression. The interpreter checks each case against
the value of the expression until a match is found. If nothing matches, a default condition
will be used.
switch
(expression) {
case condition 1: statement(s)
break;
case condition 2: statement(s)
break;
...
case condition n: statement(s)
break;
default: statement(s)
}
The break statements indicate the end of a
particular case. If they were omitted, the interpreter would continue executing
each statement in each of the following cases.
The while Loop
The most basic loop in JavaScript is the while loop
which would be discussed in this chapter. The purpose of a while loop
is to execute a statement or code block repeatedly as long as an expression is
true. Once the expression becomes false, the loop terminates.
Syntax
The syntax of while loop in
JavaScript is as follows −
while (expression) {
Statement(s) to be executed if expression is true
}
The do...while Loop
The do...while loop is
similar to the while loop except that the condition check
happens at the end of the loop. This means that the loop will always be
executed at least once, even if the condition is false.
Syntax
The syntax for do-while loop
in JavaScript is as follows −
do {
Statement(s) to be executed;
} while (expression);
The For Loop
The flow chart of a for loop in
JavaScript would be as follows −
The 'for' loop is the most compact form of looping. It
includes the following three important parts −
·
The loop initialization where we initialize our
counter to a starting value. The initialization statement is executed before the
loop begins.
·
The test statement which will test if a given
condition is true or not. If the condition is true, then the code given inside
the loop will be executed, otherwise the control will come out of the loop.
·
The iteration statement where you can increase or
decrease your counter.
You can put all the three parts in a single line separated by
semicolons.
Syntax
The syntax of for loop
is JavaScript is as follows −
for (initialization; test condition; iteration statement) {
Statement(s) to be executed if test condition is true
}
For-In Loop
The for...in loop is
used to loop through an object's properties. As we have not discussed Objects
yet, you may not feel comfortable with this loop. But once you understand how
objects behave in JavaScript, you will find this loop very useful.
Syntax
The syntax of ‘for..in’ loop is −
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.
Loop Controls
JavaScript provides full control to
handle loops and switch statements. There may be a situation when you need to
come out of a loop without reaching its bottom. There may also be a situation
when you want to skip a part of your code block and start the next iteration of
the loop.
To handle all such situations,
JavaScript provides break and continue statements.
These statements are used to immediately come out of any loop or to start the
next iteration of any loop respectively.
The break Statement
The break statement,
which was briefly introduced with the switch statement, is
used to exit a loop early, breaking out of the enclosing curly braces.
The flow chart of a break statement would look
as follows −
The continue Statement
The continue statement
tells the interpreter to immediately start the next iteration of the loop and
skip the remaining code block. When a continue statement is
encountered, the program flow moves to the loop check expression immediately
and if the condition remains true, then it starts the next iteration, otherwise
the control comes out of the loop.
Function Definition
Before we use a function, we need to
define it. The most common way to define a function in JavaScript is by using
the function keyword, followed by a unique function name, a
list of parameters (that might be empty), and a statement block surrounded by
curly braces.
Syntax
The basic syntax is shown here.
<script type = "text/javascript">
<!--
function functionname(parameter-list) {
statements
}
//-->
</script>
Function Parameters
Till now, we have seen functions
without parameters. But there is a facility to pass different parameters while
calling a function. These passed parameters can be captured inside the function
and any manipulation can be done over those parameters. A function can take
multiple parameters separated by comma.
The return Statement
A JavaScript function can have an
optional return statement. This is required if you want to
return a value from a function. This statement should be the last statement in
a function.
For example, you can pass two numbers
in a function and then you can expect the function to return their
multiplication in your calling program.
What is an Event ?
JavaScript's interaction with HTML is
handled through events that occur when the user or the browser manipulates a
page.
When the page loads, it is called an
event. When the user clicks a button, that click too is an event. Other
examples include events like pressing any key, closing a window, resizing a
window, etc.
Developers can use these events to
execute JavaScript coded responses, which cause buttons to close windows,
messages to be displayed to users, data to be validated, and virtually any
other type of response imaginable.
Events are a part of the Document
Object Model (DOM) Level 3 and every HTML element contains a set of events
which can trigger JavaScript Code.
Please go through this small tutorial
for a better understanding HTML Event Reference. Here we will see a few
examples to understand a relation between Event and JavaScript −
onclick Event Type
This is the most frequently used event
type which occurs when a user clicks the left button of his mouse. You can put
your validation, warning etc., against this event type.
onsubmit Event Type
onsubmit is an event that occurs when you try to submit a form.
You can put your form validation against this event type.
onmouseover and onmouseout
These two event types will help you
create nice effects with images or even with text as well. The onmouseover event triggers when you bring
your mouse over any element and the onmouseout triggers when you move your mouse out from that element.
What are Cookies ?
Web Browsers and Servers use HTTP
protocol to communicate and HTTP is a stateless protocol. But for a commercial
website, it is required to maintain session information among different pages.
For example, one user registration ends after completing many pages. But how to
maintain users' session information across all the web pages.
In many situations, using cookies is
the most efficient method of remembering and tracking preferences, purchases,
commissions, and other information required for better visitor experience or
site statistics.
How It Works ?
Your server sends some data to the
visitor's browser in the form of a cookie. The browser may accept the cookie.
If it does, it is stored as a plain text record on the visitor's hard drive.
Now, when the visitor arrives at another page on your site, the browser sends
the same cookie to the server for retrieval. Once retrieved, your server
knows/remembers what was stored earlier.
Cookies are a plain text data record of
5 variable-length fields −
·
Expires − The date the cookie will expire. If
this is blank, the cookie will expire when the visitor quits the browser.
·
Domain − The domain name of your site.
·
Path − The path to the directory or web page that set the cookie.
This may be blank if you want to retrieve the cookie from any directory or
page.
·
Secure − If this field contains the word
"secure", then the cookie may only be retrieved with a secure server.
If this field is blank, no such restriction exists.
·
Name=Value − Cookies are set and retrieved in the
form of key-value pairs
Cookies were originally designed for
CGI programming. The data contained in a cookie is automatically transmitted
between the web browser and the web server, so CGI scripts on the server can
read and write cookie values that are stored on the client.
JavaScript can also manipulate cookies
using the cookie property of the Document object.
JavaScript can read, create, modify, and delete the cookies that apply to the
current web page.
Storing Cookies
The simplest way to create a cookie is
to assign a string value to the document.cookie object, which looks like this.
document.cookie = "key1 = value1;key2 = value2;expires = date";
Here the expires attribute
is optional. If you provide this attribute with a valid date or time, then the
cookie will expire on a given date or time and thereafter, the cookies' value
will not be accessible.
Note − Cookie values may not include semicolons, commas, or
whitespace. For this reason, you may want to use the JavaScript escape() function to encode the value
before storing it in the cookie. If you do this, you will also have to use the
corresponding unescape() function when you read the cookie
value.
Comments
Post a Comment