Javascript Do While Loops

There’s another, less common type of loop, known as a do/while loop. This type of
loop works nearly identically to a while loop. Its basic structure looks like this:

do {
// javascript to repeat
} while (condition) ;

do {
var luckyNumber = prompt('What is your lucky number?','');
luckyNumber = parseInt(luckyNumber, 10);
} while (isNaN(luckyNumber));

Save this file and preview it in a web browser. Try typing text and other nonnumeric
symbols in the prompt dialog box. That annoying dialog box continues
to appear until you actually type a number.

Javascript For Loops

JavaScript offers another type of loop, called a for loop, that’s a little more compact
(and a little more confusing). For loops are usually used for repeating a series of
steps a certain number of times, so they often involve some kind of counter variable,
a conditional test, and a way of changing the counter variable. In many cases,
a for loop can achieve the same thing as a while loop, with fewer lines of code. For
example.

for (var num=1; num<=100; num++) {
document.write('Number ' + num + '<br>');
}


var days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday','Friday', 'Saturday', 'Sunday'];
for (var i=0; i<days.length; i++) {
document.write(days[i] + ', ');
}

Since for loops provide an easy way to repeat a series of steps a set number of times,
they work really well for working through the elements of an array. The while loop
in Figure 3-5, which writes each item in an array to the page, can be rewritten using
a for loop,

Javascript While Loops

A while loop repeats a chunk of code as long as a particular condition is true; in other
words, while the condition is true. The basic structure of a while loop is this:

while (condition) {
// javascript to repeat
}

The first line introduces the while statement. As with a conditional statement, you
place a condition between the set of parentheses that follow the keyword while.

Say you want to print the numbers 1 to 5 on a page. One possible way to do that is
like this:

document.write('Number 1 <br>');
document.write('Number 2 <br>');
document.write('Number 3 <br>');
document.write('Number 4 <br>');
document.write('Number 5 <br>');

Notice that each line of code is nearly identical—only the number changes from line
to line. In this situation, a loop provides a more efficient way to achieve the same goal:

var num = 1;
while (num <= 5) {
document.write('Number ' + num + '<br>');
num += 1;
}

Javascript Array

You can access the contents of a simple variable just by using the variable’s name.
For example, alert(lastName) opens an alert box with the value stored in the variable
lastName. However, because an array can hold more than one value, you can’t just
use its name alone to access the items it contains. A unique number, called an index,
indicates the position of each item in an array. To access a particular item in an array,
you use that item’s index number. For example, say you’ve created an array with
abbreviations for the days of the week, and want to open an alert box that displayed
the first item.

var days = ['Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun'];
alert(days[0]);


Javascript Object Type


Objects are
created by using the new operator followed by the name of the object type to create. Developers
create their own objects by creating instances of the Object type and adding properties and/or
methods to it, as shown here:

var o = new Object();

Each Object instance has the following properties and methods:
constructor — The function that was used to create the object. In the previous example,
the constructor is the Object() function.

hasOwnProperty(propertyName) — Indicates if the given property exists on the object
instance (not on the prototype). The property name must be specifi ed as a string (for
example, o.hasOwnProperty(“name”)).

isPrototypeOf(object) — Determines if the object is a prototype of another object.

propertyIsEnumerable(propertyName) — Indicates if the given property can be
enumerated using the for-in statement (discussed later in this chapter). As with
hasOwnProperty(), the property name must be a string.

toLocaleString() — Returns a string representation of the object that is appropriate for
the locale of execution environment.

toString() — Returns a string representation of the object.

valueOf() — Returns a string, number, or Boolean equivalent of the object. It often
returns the same value as toString().

HTML5 Constraint Validation API

HTML5 introduces the ability for browsers to validate data in forms before submitting to the
server. This capability enables basic validation even when JavaScript is unavailable or fails to load.
The browser itself handles performing the validation based on rules in the code and then displays
appropriate error messages on its own (without needing additional JavaScript). Of course, this
functionality works only in browsers that support this part of HTML5, including Firefox 4+,
Safari 5+, Chrome, and Opera 10+.
Validation is applied to a form fi eld only under certain conditions. You can use HTML markup to
specify constraints on a particular fi eld that will result in the browser automatically performing
form validation.

Required Fields
The fi rst condition is when a form fi eld has a required attribute, as in this example:

<input type=”text” name=”username” required>

Any field marked as required must have a value in order for the form to be submitted. This
attribute applies to <input>, <textarea>, and <select> fi elds (Opera through version 11 doesn’t
support required on <select>). You can check to see if a form fi eld is required in JavaScript by
using the corresponding required property on the element:
var isUsernameRequired = document.forms[0].elements[“username”].required;
You can also test to see if the browser supports the required attribute using this code snippet:
var isRequiredSupported = “required” in document.createElement(“input”);
This code uses simple feature detection to determine if the property required exists on a newly
created <input> element.

Keep in mind that different browsers behave differently when a form fi eld is required. Firefox 4 and
Opera 11 prevent the form from submitting and pop up a help box beneath the fi eld, while Safari (as
of version 5) and Chrome (as of version 9) do nothing and don’t prevent the form from submitting.

Javascript Event Object

Properties

Different types of events have different properties, which you’ll learn
about later in the chapter. Here are a few properties common to all standard
Event objects:
■ type The type of the event, like “click,” “load,” or “keypress.”
■ target The element that originally dispatched the event. This may not
be the same as the element to which the event handler is attached.
■ currentTarget The element to which you attached the event handler.
In most cases, it is synonymous with the this keyword. If you change
the context of the event handler with call() or apply(), you can still
access the element with currentTarget.
■ eventPhase A number that indicates whether the event is currently
capturing (1), bubbling (3), or at the target element (2). Find out more
information in the “Event Bubbling and Capturing” section later in this
chapter.
■ timeStamp A number in seconds that represents the time at which the
event occurred.


<a id="link" href="http://www.google.com">Don't go to
Google</a>
var link = document.getElementById("link");
link.addEventListener("click", dontFollowLink, false);
function dontFollowLink(event) {
alert("Not going to " + this.href);
event.preventDefault();

}


In Internet Explorer, the Event object isn’t available as an argument
of the handler. Instead, it’s a property of window. To write crossbrowser
DOM Level 0 code, look for the Event object in both places.
function handler(event) {
event = event || window.event;
}

Javascript Cookies

Cookies are small strings that let you store data across page views and
sessions. These are some common uses of cookies:
1. Keeping track of whether the user has logged in to your site
2. Remembering that a user has visited a page before
3. Differentiating between fi rst-time visitors and repeat visitors
Cookies are also sent to the server with every page request. That’s how
the server knows whether the user is logged in. Because cookies add data
to the request and therefore increase the size of the request, cookie data
is limited to 4KB.
The window.document object has a funny little property called cookie.
You can use that object to read and set cookie data.
Setting Cookies
To set a cookie, just assign the name and value to document.cookie
in the following format:
document.cookie = "name=value";
You can set only one cookie at a time, but assigning another value to
document.cookie doesn’t overwrite the previous cookies, unless one of
them shares the same name. You can continue to assign name/value pairs
to document.cookie until you hit the 4KB limit enforced by the browser.
// Adding another cookie
document.cookie = "anotherName=anotherValue";
You should always pass the value part of the string through
encodeURIComponent() to make sure it doesn’t contain any illegal
characters such as spaces, commas, and semicolons.
var cookieValue = "encoded value";
document.cookie = "thirdCookie=" +
encodeURIComponent(cookieValue);
You can also set the following optional parameters that affect the



// This secure cookie will last a year
document.cookie = "name=value;max-age=" + (60*60*24*365) +
";secure;";

You’ll have to use your string manipulation skills to extract a single
cookie’s value from this string. Regular expressions come in handy here.

function getCookie(name) {
// Get each individual cookie by splitting
// on semicolons and possible spaces
var cookies = document.cookie.split(/;\s*/);
// Make a regular expression to match the name
// and value in a subpattern
var pattern = new RegExp("\\b" + name + "=(.*)");
// Check each cookie until you fi nd a match
for (var i = 0, l = cookies.length; i < l; i++) {
var match = cookies[i].match(pattern);
if (match) {
return decodeURIComponent(match[1]);
}
}
}

Javascript forEach

Looping over arrays using functions is increasingly common, especially in
certain libraries. Modern browsers support the forEach() method, but
you can also build your own.
function arrayForEach(array, loopFunc) {
// If the browser support forEach, use it because
// it will be faster
if ("forEach" in array) {
return array.forEach(loopFunc);

// Otherwise, loop over the array and pass in
// the array values to the loop function
} else {
for (var i = 0, l = array.length; i < l; i++) {
loopFunc(array[i], i, array);
}
return array;
}
}
function doSomeMath(num) {
console.log(num * 10 - 5);
}
arrayForEach([1,2,3], doSomeMath);



5
15
25

Javascript Creating Arrays

The best way to create a new array is with the array literal syntax ([]),
but the array constructor function is available too. If you pass a single
number value to the constructor function, you get an array fi lled with
that many undefi ned values.
var myArray = [];
var myFilledArray = new Array(4);
myFilledArray;
[undefi ned, undefi ned, undefi ned, undefi ned]
Properties
Like strings, arrays have one built-in property: length. This property is
equal to the number greater than the last index in the array. This is true
even if you skip some indices.
["a", 1, true, null].length;
4
var myArray = [];
myArray.length;
0
myArray[99] = 1;
1
myArray.length;
100
The new length of myArray is 100 even though it contains only one value
at index 99. All the other values are undefined.