Javascript Tutorials
Javascript Tutorials
Javascript tutorial
JavaScript History
Web pages made using only HTML are somewhat static with no interactivity and negligible user
involvement. Interactive pages can be described as those that understand and process user
behavior (actions) like mouse movements, mouse button clicks, HTML button clicks etc.
HTML tags are just instructions on document layout and structure; the display of the document
in the window is dependent on the browser. Interactive pages cannot be built with only HTML,
we need a programming language. Further, since the response time to user actions should be
quick, the programming language has to be embedded in the browser itself. (Programs residing
on servers can not bring about interactivity due to the time taken for sending the user input and
receiving the response.)
Keeping these things in mind, the people at Netscape came out with a client-side (read browser)
language that was integrated with version 2 of Netscape Navigator. They called this language
JavaScript. (Actually, JavaScript was initially christened LiveScript. Seeing the popularity
gained by Sun Systems' Java, the bigwigs at Netscape changed its name... a clever marketing
ploy. Eh?)
Microsoft's implementation of JavaScript is called JScript and was first introduced with version
3 of Internet Explorer.
JavaScript is thus, a client-side scripting language. There is also a server-side version that is used
in Active Server Pages, a technology promoted by Microsoft. This tutorial describes only client-
side JavaScript.
JavaScript enables browsers to take decisions and process information. This is the key to
interactivity.
JavaScript now
At the time of writing, JavaScript is in version 1.2 and is soon to be standardized by the
International Standards Organization.
Validate forms at the client-side saving both the precious server resources and time.
Create mouseover effects, change background color of a document with a click of a
button... interactivity!
Randomly display content without the involvement of server programs.
Move HTML elements around pages.
Change page contents dynamically.
Load content in new browser windows and frames.
Make online games.
Nature of JavaScript
JavaScript is based on Object Oriented Programming concept. Its syntax is quite similar to C,
C++ and Java. However, it is much easier to learn and implement.
JavaScript works with HTML to bring interactivity to otherwise static documents and can be
embedded inside HTML documents in three ways:
<HTML>
<HEAD>
<TITLE>Page title</TITLE>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JAVASCRIPT" TYPE="TEXT/JAVASCRIPT">
<!--
//-->
</SCRIPT>
</BODY>
</HTML>
The LANGUAGE attribute explicitly informs the browser that the enclosed code is JavaScript.
The TYPE specifies that the code is in TEXT format.
The <!-- and //--> are placed around the code and hide it from browsers that do not understand
JavaScript. I advise you to always use these "code hiding" tags since their inclusion is harmless;
however if you leave them, the document display is completely ruined in non-JavaScript
browsers.
<A HREF="http://www.webdevelopersnotes.com"
onmouseover="alert('Go back to Home Page')">
Home Page</A>
Here we have an anchor tag that surrounds some text ('Home page'). Don't worry if you can't
understand the code (you are not supposed to at this stage). Just take a note of how the code is
embedded inside the anchor tag. onmouseover is an event handler and as its name suggests, it
manages a mouse over action. In this case, onmouseover event handler triggers some response
whenever the user moves the mouse cursor over the text enclosed between the anchor tags.
//-->
</SCRIPT>
Note that the external file containing the JavaScript code has .js extension. It is included in the
HTML document through the SRC attribute that takes the URL of the file as its value.
There are three main advantages in using this technique. Firstly, you don't need to place the code
in all HTML documents, secondly, if a change is required you have to modify only one file
instead of several and thirdly, it protects (though partly!) precious code. However, the main
disadvantage is that the server has to locate and open one more file.
Equipped with this basic knowledge, let's move towards creating your first script.
For this reason I have loaded the tutorial with dozens of with examples and assignments; and we
have the first one right here.
<HTML>
<HEAD>
<TITLE>My First JavaScript</TITLE>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JAVASCRIPT" TYPE="TEXT/JAVASCRIPT">
<!--
document.write("I love JavaScript");
//-->
</SCRIPT>
</BODY>
</HTML>
Save this file with a .html or .htm extension and view it in a browser.
You can also click here to know how it looks. (This opens another window)
Explanation
document.write("I love JavaScript"); is a JavaScript statement. Note the following points:
Case-sEnSiTiViTy in JavaScript
Like other languages, JavaScript is case-sensitive. This means that DOCUMENT.WRITE will
not work. Also, a=2 is not the same as A=2.
Note: Event handlers are not case sensitive.
2. Forgetting to include the quotes results in an error. The text needs to be surrounded by
quotes and placed inside parenthesis.
3. <script language="JavaScript" type="text/javascript">
4. <!--
5. document.write("Your-name-here");
6. //-->
7. </script>
8.
9. <script language="JavaScript" type="text/javascript">
10. <!--
11. document.write("It's a good day to die");
12. //-->
13. </script>
14.
15. <script language="JavaScript" type="text/javascript">
16. <!--
17. document.write('He said, "Welcome to my world."');
18. //-->
19. </script>
20. Note: The double quotes are surrounded by single quotes.
document.write("JavaScript is <B>great</B>.");
//-->
</SCRIPT>
You'll notice that along with the text I've thrown in the HTML bold tag. HTML tags enclosed in
write() are not displayed. The browser interprets these tags accordingly and then prints the
result. In our case, the word 'great' is displayed in bold.
Click here to view the result.
//-->
</SCRIPT>
Note that I have used single quotes to enclode the text in write(). Why? Because it is my habit to
contain HTML attribute values with double quotes. If I had used double quotes to surround both
the attribute value and the text in write(), I would have received an error from the JavaScript
interpreter.
This kind of quote nesting is used often with event handlers and it's important that you remember
it.
JavaScript allows inclusion of all HTML tags in write(). You can actually build entire HTML
documentes starting from <HTML> tag!
Possible Answers
1.
2. <script language="JavaScript" type="text/javascript">
3. <!--
4. document.write('<FONT COLOR="#00FF00">Your-name-here</FONT>');
5. //-->
6. </script>
7.
8. <script language="JavaScript" type="text/javascript">
9. <!--
10. document.write("<FONT COLOR="#0000FF">your-first-name</FONT> <FONT
COLOR="#FF0000">your-last-name</FONT>");
11. //-->
12. </script>
13.
14. <script language="JavaScript" type="text/javascript">
15. <!--
16. document.write("JavaScript is truly<BR><B>Amazing</B>");
17. //-->
18. </script>
19. No error is generated, however, the tag is ignored by the browser.
Note: JavaScript is not a true Object Oriented language as C++ or Java but rather an Object
Based language.
Here are two ferocious bears and a docile bamboo eating panda. They are animals that we find in
a zoo (Its not pleasant to come across the grizzly in the wild)
Object Properties
To describe a bear or a panda, we specify its characteristics such as color, size, weight, eating
habits, the place where its found etc. These are properties of the animal.
Polar Bears
Color: White
Diet: Fish, seals... non-vegetarian
Location: The North Tundra
Panda
Color: White and Black
Diet: Bamboo shoots
Location: China
Object Methods
So what are the things a polar bear can do? It eats, runs, swims, hibernates in the winter season
etc. A Panda also eats and runs but it can also climbs trees and seldom swims!
Such actions are the functions of the animal object. Functions in object programming are called
methods.
Thus, an object can be anything, a living being, an inanimate item, a city or even an idea. An
object is described by its charateristics called properties and can preform certain functions called
methods.
JavaScript Objects
Objects in JavaScript are software entities such as the browser window or an HTML document.
Let's describe the browser window object and some its properties and methods.
A browser window object is created whenever a document is loaded in a browser.
Its Properties
Width
Height
Name
The URL of the document it displays
Its Methods
Open
Close
Resize
So, you can define a window object with its properties such as width, height, name etc. The
behavior of the window can be controlled using its methods such as open, close, resize etc.
The document displayed by the browser window object is itself an object with its own properties
and methods. Thus, the document object is contained in the window object.
Consider an analogy of our galaxy (Milky Way) object that consists of other objects such as our
solar system which further contains objects such as the Earth and the Sun. An easy way to
describe the Earth to an alien residing in some other galaxy would be:
Milky way - Solar System - Earth
Note that the above can also be written as:
Universe - Milky Way - Solar System - Earth
But since there is only one universe (hope so!), we can leave out the redundant term. Thus, the
Milky Way is a parent object to the Solar System which is itself a parent to the Earth.
JavaScript uses the period to separate the parent object from its components. Hence, to refer to
the document object we use the following notation:
window.document
A HTML Form called contactform inside the document might be referred as:
window.document.contactform
For convenience, webdevelopers name HTML elements using the NAME attribute. Thus, a text
field named address located in a form named contactform is refered as:
window.document.contactform.address
As you would have noticed, the 'window' object is the parent to all other objects, so it is not
necessary to explicitly specify it.
Possible Answers
1. There are two parent objects:
window object that contains the document.
document object that contains myimage.
2. It refers to the value of myaddress contained in myfrom located in an HTML document.
Different HTML elements have different properties. For example, a text field form object has the
following properties:
To set the value of a text field, we use the = (equal too) operator as:
This is a JavaScript statement that instructs the browser to displays the text Type your address
here in the text field add.
Possible Answers
1. document.myphoto.src = "url_of_the_image";
as in
document.myphoto.src = "http://www.webdevelopers.com/myphoto.jpg";
document.myphoto.src = "myphoto.jpg";
2. document.contactfrom.yourname.value = "some_text";
as in
Some methods take a value part inside the parenthesis. You would know this by now since you
have encountered the write() method in the previous sessions. To refresh your memory here is
the code again:
The text I Love JavaScript is passed as a value to the write() method of the document object.
The main function of this method is to take the value and display it in the browser window.
Different objects have different methods associated with them. The submit() method of a form
object causes the form to be submitted. The log() method of the Math object computes the
logarithm of the number supplied.
document.myform.submit();
causes myform to be submitted.
Math.log(2);
computes the logarithm of 2. The number is passed to the method inside the parenthesis and is
called the argument.
Similarly, in the example before, I Love JavaScript was the argument passed to the write()
method.
1. What do you think following methods do?
a. Math.tan(3);
b. Math.sqrt(4);
c. document.write("www.webdevelopersnotes.com");
d. window.close();
e. window.scroll();
2. Which method is used to open a new document window? (Take a guess!)
Possible Answers
a. Computes the tangent of 3.
b. Computes the square root of 4.
c. Prints wwww.webdevelopersnotes.com in the document.
d. Closes a window.
e. Causes the window to scroll.
f. To open a new window we call the open() method of the window object as:
g. window.open();
Usage of the alert() method is similar to the write() method of the window object. The text
placed inside the parenthesis is displayed on the pop-up box.
Since it's not necessary to specify the window object we can leave it out from the code. Thus, the
following code will function equally well as the one above.
\n: Inserts a new line and causes the text following it to be placed on that line.
\t: Inserts a tab
\r: Carriage return
\b: Backspace
\f: Form feed
\': Single quote
\": Double quote
\\: Backslash
(Note: there are other escape sequences that consist of the backslash and hexadecimal digits.
Their use is rare ... atleast I have never used them!)
alert("JavaScript\nis\na\nclient-side\nprogramming\nlanguage");
This looks really messed up. Click here to see the result.
You'll notice that new lines have been introduced at each occurence of the \n escape character.
Possible Answers
1. alert("your-name");
2.
3. alert("First-name\n\n\n\nLast-name");
4. To insert three blank lines we use the newline escape character 4 times. (The last line is
not blank ... it contains your last name).
5. \a is simply displayed as the alphabet "a".
In order to display the backslash, we have to precede it with another backslash character.
6. document.write("\\a");
7. alert("He said \"JavaScript's the best!\"");
8. Note the escaped double quotes.
9. alert("1\n\t2\n\t\t3");
10. \t inserts a tab.
Playing the interactivity game is not very difficult. Each object has its properties and methods
placed at JavaScript's disposal and modifying these properties through JavaScript brings your
pages alive.
Take the example of a image rollover effect. The logic is quite simple. Whenever the mouse
pointer passes over the image the event is captured with the onmouseover event handler that can
then change the value of the src property associated with the image object to another URL. Thus,
a new image (with a new URL) is loaded in place of the old one.
The onmouseover is an event handler associated with the link object. (As far as JavaScript is
concerned, any thing placed between the <A> - </A> is a link object). The value of the event
handler is a small JavaScript code. Whenever the mouse pointer is moved over the link, this
event handler captures the action and instructs the browser to display an alert box.
Pass your mouse pointer over the link below to see how it works.
Home Page
<A HREF="http://www.webdevelopersnotes.com"
onmouseover="window.status = ('Go back to Home Page')">
Home Page</A>
Home Page
Here the onmouseover event handler modifies the status property of the window object. It
directs the browser to print Go back to Home Page on the status bar.
Note that in the first example, onmouseover calls the alert method while in the second it modifies
a property value.
<A HREF="http://www.webdevelopersnotes.com"
onmouseover="document.bgColor='#EEEECC'">
Home Page</A>
Home Page
This time, onmouseover changes the bgColor (background color) property of the document
object and sets it to a light grey color.
Possible Answers
1. <A HREF="somelink.html" onmouseover="alert('your-name')">Link</A>
2. Note: The single quotes are nested inside double quotes.
3. <A HREF="somelink.html" onmouseover="document.bgColor='#FF0000'">Change
Background color to red</A>
4. Note: bgColor is a property of the document object since it's the document object that
controls the background color of the page. The event handler is case insensitive since its a
part of the HTML. However, the code is exclusively JavaScript's domain and is sensitive
to case. Thus, bgcolor will not work (and probably throw error under some browsers).
The correct usage is bgColor with the capital C.
5. <A HREF="somelink.html" onmouseover="document.bgColor='#FF0000'">Change
Background color to red</A>
6.
7. <A HREF="somelink.html" onmouseover="document.bgColor='#FFFFEE'">Change
Background color to pale yellow (original color)</A>
8.
<A HREF="http://www.webdevelopersnotes.com/"
onmouseover="window.status='Go Back To Home Page';
document.bgColor='#EEEEEE'">
Change the background color and put a message on the status bar
</A>
Note: The two JavaScript statements window.status='Go Back To Home Page' and
document.bgColor='#EEEEEE' are separated by a semicolon which informs the JavaScript
interpreter to treat the two as individual statements.
Each of these statements carries an instruction for the interpreter. The first one changes the
message on the status bar while the second changes the background color. The statements are
executed in the order they appear. You might not notice it with this example as the execution
very fast.
Change the background color and put a message on the status bar
A similar example is to bring up an alert box and change the background color.
<A HREF="http://www.webdevelopersnotes.com/"
onmouseover="window.alert('Go Back To Home Page');
document.bgColor='#EEFFFF'">
Change the background color and bring up an alert box</A>
Change the background color and bring up an alert box
When you pass the mouse cursor over the link above, you'll notice that the alert box is displayed
first, JavaScript execution is stopped. Once the OK button is clicked the next statement is
executed that changes the background color.
<A HREF="http://www.webdevelopersnotes.com/"
onmouseout="document.bgColor='#FFEEEE'">
Changes the background color when the mouse
is placed and then taken off the link
</A>
Take your mouse pointer gradually over the link and keep it there... nothing happens; however,
the moment you take it off, the background color is changed.
Changes the background color when the mouse is placed and then taken off the link
<A HREF="http://www.webdevelopersnotes.com/"
onmouseover="document.bgColor='#FFFF00'"
onmouseout="document.bgColor='#FFFFEE'">
Move your mouse over me!
</A>
onmouseover changes the background color to a bright yellow while onmouseout changes it back
to the original color.
(Moving the mouse over the link repeatedly will result in a bad headache!)
I hope by now, you would have got the hang of using event handlers. Let's see if you are able to
crack the following exercise:
1. Construct a link that changes the background color to red and displays Dangerous color
message in the status bar when the mouse is passed over it. When the mouse is taken off
the link the page should return to the original background color.
2. Now change the code so that the message is displayed in an alert box instead of the status
bar.
Possible Answers
1. <A HREF="somelink.html"
onmouseover="document.bgColor='#FF0000';window.status='Dangerous
color'" onmouseout="document.bgColor='#FFFFEE'">Link</A>
2. Check the result: Link
3. <A HREF="somelink.html"
onmouseover="document.bgColor='#FF0000';alert('Dangerous color')"
onmouseout="document.bgColor='#FFFFEE'">Link</A>
4. Check the result: Link
<A HREF="javascript:void(0)"
onmouseover="document.bgColor='#EEEEEE'">
Dead link</A>
Link
You may wonder why we can't use HREF="" (a blank or no value) instead of
HREF="javascript:void(0)". The reason is that a blank or null value for HREF is interpreted as
the URL of the directory. Thus, in our case if we use HREF="", the browser actually sees it as
http://www.webdevelopersnotes.com/tutorials/javascript/.
javascript:void(0) returns (not specifies!) a null value. Hence, whenever a link is clicked no
page is loaded.
<A HREF="javascript:void(0)"
onclick="alert('You clicked on the link')">
Dead link</A>
Dead link
<A HREF="javascript:void(0)"
ondblclick="alert('You double clicked on the link')">
Double click on me</A>
Double click on me
1. Construct a link that changes the background color to light blue (#99CCFF) when
clicked.
2. Change the code so that clicking on the link also displays an alert box.
3. How about a link that changes the background color to red when clicked and back to the
original when the mouse pointer is moved off the link?
4. The open() method of the window object is employed to open a new window. Construct a
link that opens a new window when clicked.
Possible Answers
1. <A HREF="javascript:void(0)"
onclick="document.bgColor='#99CCFF'">Link</A>
2. Check: Link
3. <A HREF="javascript:void(0)"
onclick="document.bgColor='#99CCFF';alert('I am an alert
box')">Link</A>
4. Check: Link
5. <A HREF="javascript:void(0)" onclick="document.bgColor='#FF0000'"
onmouseout="document.bgColor='#FFFFEE'">Link</A>
6. Check: Link
7. <A HREF="javascript:void(0)" onclick="window.open()">Link</A>
8. Check: Link
We have already seen that if we provide the URL of a document through the first argument, it
will be loaded in the new window.
NAME: specifies a name for the new window that can then be used as value for the TARGET
attribute of <A> tags.
FEATURES: let you define properties of the window such as width, height, presence or absence
of scrollbars, location bar, stauts bar etc. The list of features is quite daunting so we shall go over
them gradually.
REPLACE: takes a boolean value... we won't bother ourselves with this argument!
<A HREF="javascript:void(0)"
onclick="window.open('welcome.html','welcome')">
Open a new window</A>
This opens a new window 300 pixels in width and 200 pixels in height. Pay close attention to
how the features are written. The two features (width and height) are enclosed by a pair of quotes
without any spaces and there are no quotes surrounding the values.
The width and the height take a number (pixels) as value, for other features the value is either a
yes or no.
<A HREF="javascript:void(0)"
onclick="window.open('welcome.html',
'welcome','width=300,height=200,menubar=yes,status=yes')">
Open a new window</A>
This window has the menu and the status bars. The others are absent since we didn't specify
them.
<A HREF="javascript:void(0)"
onclick="window.open('welcome.html',
'welcome','width=300,height=200,menubar=yes,status=yes,
location=yes,toolbar=yes,scrollbars=yes')">
Open a new window</A>
Our event handler script is becoming unmanageble... it's too long. In the next session we look at
JavaScript functions and how they can contain blocks of code that can be used again and again.
But before that, here is a small novelty for Internet Explorer users.
The fullscreen feature is specific to this browser and displays the document on the entire screen.
A neat effect... sort of! Click on the F11 to remove the full screen display.
<A HREF="javascript:void(0)"
onclick="window.open('welcome2.html',
'welcome','fullscreen=yes,scrollbars=yes')">
Open a full screen window</A>
1. Write the code for opening a new window with a width of 400 pixels, height 200 pixels,
scrollbars, menubars.
2. If the method for opening windows is open(), what do you think will be the method for
closing windows?
3. What happens if you open a new window omitting the features argument?
Possible Answers
1. window.open('url','name','width=400,height=200,scrollbars=yes,menubar=yes');
2. window.close()
3. The new window carries all the features.
A function consists of the function keyword, the name of the function followed by a pair of
parenthesis and lastly, the JavaScript statement/s enclosed by curly braces.
You can give any name to the function as long as it is not a JavaScript reserved keyword. (The
list of reserved keywords can be found here.)
The function name can contain only alphanumeric characters (alphabet and digits) and the
underscore. Also, the name cannot begin with a numeral.
Remember, function names are case sensitive, thus, alert_box is not the same as Alert_box.
The function block can contain several JavaScript statements enclosed between the curly braces.
Calling functions
Calling a function is simple. You have to specify its name followed by the pair of parenthesis.
alert_box();
//-->
</SCRIPT>
It's good programming practice to place all functions in the HEAD section of the HTML
document between the <SCRIPT> - </SCRIPT> tags. Function calls, on the other hand, can
occur in any part of the document (where ever they are needed!), even inside event handler code.
You'll notice that a function call looks very similar to calling a method. Now, wasn't that simple?
function open_win()
{
window.open('welcome.html','welcome','width=300,height=200,
menubar=yes,status=yes,location=yes,
toolbar=yes,scrollbars=yes');
}
//-->
</SCRIPT>
Note: the entire JavaScript code should be placed on a single line. For clarity, I have put the code
on multiple lines.
We name this function open_win and place it in the HTML head section.
Possible Answers
1. As many times as you want.
2. Yes! we've already seen this through examples.
3. Curly braces are needed to contain the JavaScript statements forming a block.
4. There are three mistakes in the code
a. The function name is invalid. The name cannot begin with a numeral.
b. The pair of parenthesis following the name are missing
c. In the alert statement, single quotes are used instead of double quotes to close
mark the end.
5. The function consists of four JavaScript statements.
6. function some_name()
7. {
8. alert("some_text");
9. window.status='some_message';
10. document.bgColor='some_color';
11. window.open("url","name","width=300,height=200");
12. }
13. If you remember, the text contained in the alert() method is called an argument. We've
passed the url, the name and the features as arguments to the open() method of window
object. Similarly, functions can take arguments too. The arguments are supplied as a
comma separated list. More on this in later sessions.
Variable names
Once a value is stored in a variable it can be accessed using the variable name. A variable name
can consist of alphanumeric characters and the underscore. It cannot begin with a numeral,
though. Note that variable names are case sensitive and my_name is not the same as MY_name.
var your_name;
var total;
Here two variables, your_name and total have been initialized. However, no value has been
assigned to these variables. The process of initialization just sets a memory location for a
variable.
You can test for the value of an initialized variable through the alert() method. JavaScript returns
the value "undefined".
alert(your_name);
Click here to test the alert method
Note: The variable in the above alert() method is not surrounded by quotes.
sum_total = 2001;
[The equal to sign is know as the Assignment operator in JavaScript. It acts on two operands,
one on its right and the other on its left. The function of this operator is to assign or change
variable values.]
When working with JavaScript variables, it's advisable that you initialize them with the var
keyword at the very beginning of the script. This will prevent unnecessary errors.
Data types
Variables store data. In JavaScript, this data can be of several types:
Was this confusing? To simplify the explanation, let's look at the first two data types.
Thus, floating point numbers can consists of either a decimal number or a very large or small
number that is represented using the e notation.
Numeric data types can be manipulated using mathematical operators such as addition,
subtraction, multiplication etc. We will look at these very shortly.
Answers
1. A variable name cannot begin with a numeral.
2. String
function open_win(url_add)
{
window.open(url_add,'welcome',
'width=300,height=200,menubar=yes,status=yes,
location=yes,toolbar=yes,scrollbars=yes');
}
The function has a parameter url_add inside the parenthesis. It occurs in the function once again
at the place where we specify the URL for the new window, however, this time it's not enclosed
in quotes.
To call the open_win function, we pass an argument which is the url address of the document we
plan to display in the new window.
open_win("welcome.html");
When open_win is called, we pass the url as an argument. Note that the url is a string data type
and has to be enclosed in quotes.
The function picks up the argument and puts it in the value of the url_add variable. The variable
containing a URL address (welcome.html) and is used inside the function in place of the actual
URL string.
<A HREF="javascript:void(0)"
onclick="open_win('welcome.html')">Welcome message</A>
So if we want to open 10 pop-up windows each displaying a different URL, we call the function
10 times, each time using with a different URL as argument. The beauty is that we don't have to
write separate functions for displaying pop-up windows with individual URL addresses; the
same function is sufficient.
function change_back(colorval)
{
document.bgColor=colorval;
}
<A HREF="javascript:void(0)"
onmouseover="change_back('#CCCC99')">
Background Color 1</A>
Each link below, passes a different color code to the function. Move your mouse over the links
below to see the effect.
Background Color 1
Background Color 2
Background Color 3
Background Color 4
Background Color 5
Background Color 6
Background Color 7
Background Color 8
Background Color 9
Original Color
1. Create a function that loads a new window 300 X 200 pixels in dimensions.
2. Now change the code above so that you can pass the URL as argument to the function
Possible Answers
1. function open_win()
2. {
3. window.open('url','name','width=300,height=200');
4. }
5.
6. function open_win(doc_url)
7. {
8. window.open(doc_url,'name','width=300,height=200');
9. }
10. Note: the argument occurs without the quotes
var lucky_number = 7;
Operators work on one or more values, called operands to yield a single result. An expression is
a combination of operands and operators.
In the first example above, the assignment operator (=) sets the value of lucky_number variable
to 7. The two values on the left and right hand side of the operator (lucky_number and 7) are,
thus, the operands. The full JavaScript statement is an expression.
Arithmetic Operators
Arithmetic operators work on one or more numeric values yielding a single result.
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
++ Increment by 1
-- Decrement by 1
Addition
var a = 4 + 10;
In the expression above, the addition operator adds 4 and 10 to yield 14 and the assignment
operator assigns this value to the variable a.
var b = 3;
(variable b is assigned a value of 3)
b = 10 + 5 + 3 + 6;
(b now equals 24)
Subtraction
var c = 40 - 5;
(c = 35)
Multiplication
var d = 100 * 4;
(d = 400)
Division
var e = 100 / 4;
(e = 25)
var a = 4;
var b = 6;
var c = 10;
var d = 3;
var e = a + b + c;
(e = 20)
var f = b - c + a;
(f = 0)
var g = b / d + b;
(g = 8)
What is Modulus?
The JavaScript Modulus Arithmetic operator returns the remainder left after division.
var a = 70 % 16;
var b = 64 % 8;
(b equals 0)
var a = 5;
a++; (a = 6)
var b = 10;
b--; (b = 9)
The function of the increment operator (and the decrement operator) can also be achieved by
adding the digit 1 to the variable as:
a = a + 1;
OR
b = b - 1;
Result:
Now,
Result:
page2 = "151";
page3 = "152";
The reason is that the variable page stores digits as string data, the + sign, in this case behaves as
the string concatenation operator and not as the arithmetic addition operator.
Possible Answers
1. Calculations perfomed using the increment or decrement operators are much faster. There
is also the ease of use, especially when you learn to use these in for loops.
2. r = 4, because 46 divided by 7 leaves 4 as a remainder.
3. a = 20
4. The + string operator.
5. t = "Made 4 U and Me"
a++;
b--;
OR
++a;
--b;
When these operators are used as prefixes, JavaScript first adds one to the variable and then
returns the value. When used as suffixes, the value is first returned and then the variable is
incremented. Let's know more about this:
var a = 5;
b = a++;
(b contains the initial value of a, which is 5.
a, on the other hand is now equal to 6)
var a = 5;
c = ++a;
(In this case, JavaScript first adds 1 to a, changing
its value to 6. This value is returned to c.
Thus, c = 6)
Start by adding 25 to 100 and then multiplying the result with 4... yields 500.
Multiplying 100 by 4 and then adding 25... yields 425.
Let's consider a situation where you plan to display the name of the visitor on the page. To do
this you would first have to get the visitor's name (we'll shortly see how to achieve this), store it
in a variable and send the result to the document.write() method. Here we'll examine how we can
pass variables to JavaScript methods.
We've assumed that the visitor's name is stored in a variable called vis_name. Note how the
variable is written outside the quotes of the write() method. If this variable was included in the
quotes, JavaScript would have written vis_name instead of the name of the visitor. Similarly, for
the alert() method, we would pass the value as:
Remember, a variable should be placed outside the quotes to display its value.
1. What do you think will be written on the window by the following code?
2. var url = "http://www.webdevelopersnotes.com/";
3.
4. document.write("Welcome to <B>" + url + "</B>");
5. What will be displayed on the alert box?
6. var my_movie = "Godfather";
7.
8. alert("My favorite movie is my_movie");
Possible Answers
1. Welcome to http://www.webdevelopersnotes.com
(The variable lies outside the parenthesis, hence its value is displayed.)
2. My favorite movie is my_movie
(JavaScript cannot interprets my_movie as a variable since its enclosed in the quotes.
3. The sum total is sum_total
(Variable placed inside quotes. JavaScript makes no discrimination between a string data
or numeric data when displaying variable values)
4.
5. function msg(name)
6. {
7. alert("Welcome " + your_name_here);
8. }
9.
10. // Calling the function
11.
12. msg("your_name_here");
13.
14. function msg(name)
15. {
16. window.defaultStatus("Welcome " + your_name_here);
17. }
18.
19. // Calling the function
20.
21. msg("your_name_here");
22.
23. You might ask why we use defaultStatus instead of simply window.status. The reason is
that window.status is associated only with event handlers and cannot recognize a variable
even if its outside the quotes.
When you are learning a new programming language it takes time to understand its syntax. Your
code might have a few bugs; it's okay as long as you know how to correct them.
JavaScript beginners mainly make three kinds of errors
if (condition)
{
statements to execute
}
When JavaScript encounters an if statement, it checks the condition. If and only if, it is found to
be true, the statements enclosed within the curly braces are executed. Note, the condition is
always enclosed by a pair of parenthesis.
var a = 5;
var b = 5;
if (a == b)
{
alert("The two quantities are equal");
}
First, two variables are initialized and assigned the same numeric value (5). The if statement then
checks for their equality and pops-up an alert box if the two variables are equal.
The == comparison operator does the job of checking the two variables. The other Comparison
operators are:
!= Not equal to
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
The confirm box has two buttons, an "OK" and a "Cancel" button. When the user clicks on "OK"
the value 'true' is returned, while clicking on "Cancel" returns 'false'. We can capture this
returned value in a variable and test it through an if statement. Let's look at a similar real world
example:
if (response == false)
{
alert("Go thru the sessions again");
}
Possible Answers
1. The window object.
2. false
3. a and b are not equal, the condition will be TRUE since we are checking for inequality.
4. Yes! the statements will be executed
It's rather strange but JavaScript does not differentiate between the two data types with
the comparison operator.
5. If the user clicks on the "OK" button, an alert box pops up. Nothing happens if "Cancel"
is clicked.
Just like the conditions of everyday life, the conditional if statement in JavaScript has an else
clause. It allows us to take the alternate path when the condition in if is false.
if (weather == "raining")
{
alert("I'll stay at home");
}
else
{
alert("I'll go out for a stroll");
}
We can extend our if statement we met in the previous session to construct a better confirm box.
if (response == true)
{
alert("Okay, let us continue");
}
else
{
alert("Go thru the previous session again");
}
Note that the statements in the else block are executed ONLY when the condition in if is false.
The following code checks if a number is even or odd and displays an appropriate alert box.
var n = "23";
if (n%2)
{
alert("Number is Odd");
}
else
{
alert("Number is even");
}
Conditions in JavaScript can either be true or false. A false condition is one in which the result
is zero or null. In the code above, the remainder left after dividing an even number by 2 will be
zero (number modulus 2 = 0), hence the condition will evaluate to false. However, if the number
is odd, the remainder left after dividing the number by 2 will be 1 and the condition will evaluate
to true. Thus, the code block inside else will be executed when the number is even. If this sounds
confusing, go through the code and read this section once again.
var a = 10;
if (!(a == 10))
{
alert("The magic of JavaScript");
}
else
{
alert("The beauty of JavaScript");
}
In the code above, we assign variable a a value of 10. The if statement checks the value of the
variable and displays an alert.
So which alert is displayed?
Since a is 10, the condition (a = 10) returns true. However, the NOT operator reverses this
condition to false, hence the alert in the else block is displayed.
Possible Answers
1. The condition in if checks if the value of variable today is equal to "Sunday". In our case,
this is false, hence the else code block is executed and "I have tons of work to do" is
displayed in an alert.
2. Variable a is 40 and b is 60, hence a is less than b. The condition in the inner pair of
brackets is thus 'false'. However, the ! operator (also called the NOT operator) changes it
to 'true'. The function of the NOT operator is to reverse a condition. An alert box with
"Hello" will be printed when this code is executed.
3. The 'true' condition is changed to 'false' by the first NOT operator. It then changes back to
'true' when it encounters the second NOT operator.
Because of browser incompatibility issue in DHTML, some web develpers make two versions of
their site, one that is compatible with Internet Explorer and the other that contains Netscape
Navigator specific code. These developers use a browser detection script to transfer the visitor to
the respective site.
We'll concentrate only on Internet Explorer and Netscape Navigator since they are the most
prominent browsers on the Internet.
To automatically transfer the visitor, we have to take the help of location property of the
window object. Let's look at the code.
//-->
</SCRIPT>
Possible Answers
1. The browser name
2. The location property takes a URL as value. This can either be a relative or an absolute
URL.
To start working with dates and time, we first initialize a variable and assign it a value with the
new operator and the Date() constructor. The main function of the new operator with Date()
constructor is to create a new date object that is stored in the variable. Here is the code:
Thus, variable d contains a new date object. We can now call the various methods of this date
object.
Now we can easily display the date, month and year in an alert box, using the values stored in
respective variables.
The eagle-eyed would have noticed that the month digit is one less than the present month.
Hence, if you want to display the month, increment the value returned by getMonth() by 1. The
corrected code should be:
t_mon++;
alert("Today's date is " + t_date + "-" + t_mon + "-" + t_year);
Similarly, we can get the time using the variables that store hours, minutes, seconds and
milliseconds values.
In the next session we'll see how we can display a greeting based on the client time.
1. Which method of the date object is used to get four digit year value?
2. What is the value of variable mon assuming that the present month is March?
3. var t = new Date();
4. var mon = t.getMonth();
5. The hours are represented in 24 hour clock. If midnight is 0 what is noon?
Possible Answers
1. The getFullYear() method.
2. Variable mon would be 2 since JavaScript returns month values one less than the present
month. January is 0, February is 1 and so on till December, which is 11.
3. Noon will be 12.
JavaScript - Else If
We've already learnt that conditions can take one of the possible two paths. That is, when the
condition is 'true' the if statement block is executed while the statement block in else is executed
when the condition is 'false'. However, as in life, things are rarely black or white... there are
always shades of grey.
The JavaScript if - else statements also provides for else if clauses through which we can make
additional branches to the condition.
if (number > 0)
{
alert("Number is a positive integer");
}
else if (number < 0)
{
alert("Number is a negative integer");
}
else
{
alert("Number is 0");
}
Note that the else if clause is followed by another condition placed between parenthesis. If this
condition is true, the statement inside the else if block are executed.
The code above checks the value of variable number. When number is greater than 0, the
statements in if block are executed and when number is less than 0, the statements in else if
block take over. Finally, if the number is equal to zero, the conditions in if and else if are 'false'
and the program execution falls to the statements in else clause block.
When you first entered this page, you received a greeting. This greeting is customized according
to the time on the client (your) machine. Let's see how it works.
if (t_hour <= 3)
{
alert("Hello dear visitor,\nWorking late aren't we?");
}
else if (t_hour > 3 && t_hour < 12)
{
alert("Good morning dear visitor");
}
else if (t_hour >=12 && t_hour <= 16)
{
alert("Good afternoon dear visitor");
}
else
{
alert("Good Evening dear visitor");
}
We first initialize a variable using the new operator with the Date() contruct. The value of hours
is stored in t_hour variable by employing the getHours() method of the date object. The value of
t_hour variable is then passed through if-else if-else conditions. Thus, depending on the time of
the day (time in hours), a greeting is displayed in an alert box.
You'll recall that JavaScript clock is a 24 hour clock.
When t_hour is less than equal to 3 (0, 1, 2, or 3): alert box displays "Hello dear
visitor,\nWorking late aren't we?".
When t_hour is more than 3 AND less than 12: alert box displays "Good morning dear
visitor".
If the value of t_hour is greater than equal to 12 AND less than equal to 16: "Good
afternoon dear visitor" is displayed in the alert box.
For all other values of t_hour (17, 18, 19, 20, 21, 22, and 23): alert box displays "Good
Evening dear visitor".
You can check this script by changing the time on your machine and clicking on the above link.
if (number > 4)
{
statements...
}
The above condition checks is variable number is greater than 4. To check if this variable value
lies between 10 and 4, we employ the && operator.
Thus, the statements inside the if block will be executed if number equals 5, 6, 7, 8 or 9.
Now, if we want to display an alert box if the value of number variable is less than 20 or more
than 50, we use the || operator.
In the code above, an alert box will be displayed if number is 18, 5, -435, 51, 324... However, if
the value of number lies between 20 and 50 (included 20 and 50), no alert box will be displayed.
Possible Answers
1. An else if clause is used in an if statement when you would like to have more than 2
branches for the condition.
2. You can use any number of else if clauses as long as the conditions associated with each
are mutually exclusive.
3. alert("Above average performance");
In this session we'll look at the JavaScript prompt. The prompt() is a method of the window
object, just like alert() or confirm().
The format for prompt() is similar to alert() or confirm() except for one addition.
In addition to the "OK" and "Cancel" buttons, a prompt box also has a text field that is employed
for gathering visitor input. JavaScript lets you specify a default text for this text field. This is
optional, that is you can construct a prompt() without specifing the default text. In such cases,
JavaScript displays an ugly "undefined" value in the text field.
The information submitted by the visitor from prompt() can be stored in a variable, just as we
had stored the value returned by confirm().
Once we have the value, we can write a customized greeting using document.write() as I have
done or display an alert box.
It's important to remember that the value returned by prompt() and subsequently stored in a
variable will always be a string data type. This is fine if you are dealing with text, but might
present problems to the code if you plan to receive numeric data through prompt(). Javascript
provides two functions to convert this string value to a numeric data type; parseInt() and
parseFloat().
The parseInt() converts a string to an integer value while parseFloat() parses the string
converting it to a floating point number.
Note: An integer is a whole number without any fractional part while floating-point numbers
have a decimal part.
Now let's write a small script that takes a number from the visitor, checks whether its odd or
even and displays the result through an alert box.
n = parseInt(n);
if (n == 0)
{
alert("The number is zero");
}
else if (n%2)
{
alert("The number is odd");
}
else
{
alert("The number is even");
}
We can make the code above more user-friendly by introducing one more if statement that
checks for valid input.
Possible Answers
1. Prompt(), like alert() and confirm() is a method of the window object.
2. The first argument is displayed on the prompt box while the second is displayed as value
of the text field. The second argument is optional, which means that JavaScript will not
throw an error if you skip it. However, in such cases, JavaScript displays "Undefined" in
the text field.
3. String data type
4. parseFloat() converts an input to a floating-point number.
parseInt() converts the input to an integer.
5. "abcd" is a string and cannot be parsed by parseInt(). JavaScript returns NaN (Not a
Number).
6. isNaN() is employed to check if the number is valid or not.
var a = 10;
disp_a();
function disp_a()
{
var a = 20;
alert("Value of 'a' inside the function " + a);
}
We first declare a global variable a and assign it a value of 10. Then we call a function in which
we again initialize a variable named a. Since we have used the var keyword inside the function,
this variable will have a local scope. Once we come out of the function, the local variable no
longer exists and the global variable takes over.
Now, let's see how we can change the value of a global variable in a function.
var a = 10;
disp_a();
function disp_a()
{
a = 20;
alert("Value of 'a' inside the function " + a);
}
return expression
as in:
function cal_avg()
{
var avg = sum_total / n;
return avg;
}
In the above code, the value of variable avg is returned by the function.
Possible Answers
1. Local variables are initialized using the var keyword inside a function.
2. Variable sum = 1;
When the JavaScript interpreter comes across a for loop, it executes the initialization statements
and then checks the condition. Only when the condition returns 'true', the interpreter enters the
loop. After the first iteration, the updation statements are executed and then the condition is
evaluated again. This continues till the condition returns 'false' and the loop stops.
Some important points to note are:
The initialization statements are executed once; only when the for loop is encountered.
After execution of initialization statements, the condition is evaluated.
After every iteration, the updation statements are executed and then the condition is
checked.
alert(msg);
First, the variable x is initialized to 1, the condition is then evaluated. Since x is less than equal to
10, the statements inside the for loop are executed. The JavaScript interpreter then runs the
updation statement that adds 1 to variable x. The condition is again checked. This goes on till the
value of x becomes larger than 10. At this point, the statement immediately following the for
loop is executed.
alert(msg);
Possible Answers
1. The condition is evaluated at the beginning of the loop and at every iteration.
2. The initialization statements are executed only once, at the beginning.
3. Six times, when a = 0, 2, 4, 6, 8 and 10.
4. None
5. The final value of y is 360.
6.
7. var msg = "";
8. var num = 0;
9. var sum = 0;
10. var avg = 0;
11. for (var x = 1; x <= 5; x++)
12. {
13. num = prompt("This script calculates the average of 5 numbers",
"Number " + x);
14. num = parseInt(num);
15. sum = sum + num;
16. }
17. avg = sum / 5;
18. alert("The average of the 5 numbers is " + avg);
After initializing all the required variables, we run a for loop five times to gather input
from the visitor. The input is then converted to a number through parseInt() and added to
the variable sum. At the end, the average is calculated and displayed in an alert box.
19.
20. var msg = "";
21. var num = 0;
22. var sum = 0;
23. var avg = 0;
24. var t = prompt("For how many numbers would you like to find the
average?", "");
25. t = parseInt(t);
26. for (var x = 1; x <= t; x++)
27. {
28. num = prompt("This script calculates the average of 5 numbers",
"Number " + x);
29. num = parseInt(num);
30. sum = sum + num;
31. }
32. avg = sum / t;
33. alert("The average is " + avg);
while (condition)
{
...statements...
}
As long as the condition evaluates to 'true', the program execution will continues to loop through
the statements.
In the previous session, we had used the for loop to display digits 1 to 10 in an alert box. We'll
now employ the while loop to do the same thing.
Note that the initialization statement (X = 1) has been placed before the loop. The condition lies
between the parenthesis and the updation statement (x++) is present inside the statement block.
It's a common error by beginners to forget the updation statement in which case the codition will
never evaluate to 'false' and this will result in an infinite loop. To avoid such situations, my
humble advice is to write the updation statement right after starting the statement block. You can
then build the rest of the code in the statement block.
We can also employ the while loop to display the 12 times table as we had done with for.
If the condition in while evaluates to 'false' at the very beginning, the loop is skipped altogether
and program execution starts at the statement immediately following the loop.
var x = 20;
do
{
alert("The number is " + x);
x++;
}
while (x <= 10);
Click here to check the code
In the code above, the value of variable x is 20, hence the condition evaluates to 'false'. However,
the loop is executed once since the condition is presented at the end of the loop and not at the
beginning.
1. If the value of variable num is 20, how many times will the following while loop be
executed?
2. while (num <= 30)
3. {
4. ... statements ...
5. num = num + 3;
6. }
7. How many times is the while loop executed in the following code?
8. var b = 45;
9. var a = 14;
10. while (a < 50)
11. {
12. document.write("All is well with me");
13. b = b + 5;
14. }
15. If the condition evaluates to 'false', how many times is the do-while loop executed and
why?
Possible Answers
1. Four times
2. Infinite times since there is no update statement for variable a inside the while loop.
3. Once, because the condition is present at the end of the loop.
For example, continue can be employed to display only the even numbers between 1 to 20,
skipping the odd numbers.
var msg = "";
for (var x = 0; x <=20; x++)
{
if (x%2)
{
continue;
}
msg = msg + x + "\n";
}
alert(msg);
The condition in if checks for a remainder when variable x is divided by 2. Thus, for odd
numbers, the condition will be 'true' and the loop will be skipped because of continue.
1. In the code below, which numbers are displayed in the alert box?
2. var msg = "";
3. for (var x = 0; x < 10; x++)
4. {
5. if (x == 5 || x == 7)
6. {
7. continue;
8. }
9. msg = msg + x + "\n";
10. }
11. alert(msg);
12. How can you display the odd numbers between 1 to 20 WITHOUT the use of continue?
Possible Answers
1. 0, 1, 2, 3, 4, 6, 8 and 9.
2.
3. var msg = "";
4. for (var x = 1; x <= 20; x = x + 2)
5. {
6. msg = msg + x + "\n";
7. }
8. alert(msg);
OR
The onmouseover event handler is used for generating various kinds of interactivity on web
pages. It's most often used for image rollovers. Image change on mouse over is actually quite
simple once we understand the logic.
To start off, we make two images, one for mouseover and the other for mouseout.
The image that signifies mouseout is displayed in the <IMG> tag.
The image is given a name using the NAME attribute of <IMG> tag.
This tag is surrounded by <A> tags, which contain the onmouseover() and onmouseout()
event handlers.
When a mouse cursor is brought over an image, the event is captured by onmouseover().
This event handler changes the image to another by employing the src property of the
Image object.
When the mouse cursor is removed from the image, we utilize the pnmouseout() to
capture the event. This event handler changes the image back to the original.
Here are the two images I made:
We'll now construct an image tag and give the image a name using its NAME attribute.
We use icon1.gif as the value for the SRC attribute since this is the image used for mouseout.
The image is named but.
The two event handlers are placed inside the starting <A> tag.
</A>
As you would have guessed, images are a part the document object. The src property of the
image object determines the source of the image.
Thus, when the mouse cursor is brought over the image, the event is captured by onmouseover()
that changes the src property, icon2.gif in our case. The opposite happens when the mouse is
taken off the image. You should also note that the image is refered to by its name. If this was not
so, JavaScript would be confused as to which image to change!
1. Why do you require the NAME attribute of the <IMG> tag to be used for image roll-
overs?
2. How can you change an image? (The most important statement)
3. If we use onclick() event handler instead of onmouseover() and onmouseout(), will the
image change when we click on it?
Possible Answers
1. The NAME attribute is required so that JavaScript knows which image to work on.
2. An image can be changed by changing the value of it's src property through
document.image_name.src.
3. Yes, the image will change.
In the image roll-over script of the previous session, the code for changing the image was placed
inside the event handlers. This is fine if there are one or two images. In case of several images, it
is advisable to pack the code in a function that can be called repeatedly by event handlers using
different parameters.
There are two important things in an image roll-over code. One is the image name and the other
is the image source. Thus, we have to construct a function that accepts these two arguments and
changes the image source.
We can now call this function from our even handlers and pass it the two arguments.
1. You've seen how we can change an image on mouseover. How do you think, two images
can be changed with a single mouse over?
Possible Answers
1. Two images can be modified on a single mouseover by constructing a function that
changes the src property of two image objects.
To learn more about this, click here.
In the code above, the random() method returns the number which we store in the variable
rand_no and display through alert(). Click to display a random number.
You'll notice that each time you click the link a new random number is generated and displayed.
Now that we have our randomly generated number with JavaScript, let us see how we can use it
in some of our applications.
The first step is to multiply the long decimal random number generated by the random() method
with 100.
The code above will give us a random number between 0 and 10. All numbers will be a little
more than 0 and a little les than 100 - and they still have the long tail of numbers after the
decimal. The next step involves another method of the JavaScript Math() object called ceil().
Math.ceil(2.456) //gives 3
Math.ceil(46.9) //gives 47
Math.ceil(0.0006) // gives 1
To remove numbers after the decimal and provide us with an integer between 1 and 100, we will
pass the random number generated by random() to ceil().
JavaScript generates random numbers based on a formula. In a sense this is not random because
if you know the formula, you know which number will come up next. However, this works fine
for the web applications you will develop.
Get a list of 20 randomly gerenated numbers between 1 and 100.
Math.floor() method
The floor() rounds a number down to the lower integer. Thus:
Math.floor(2.456) //gives 2
Math.floor(46.9) //gives 46
Math.floor(0.0006) // gives 0
Math.floor(1.0006) // gives 1
Math.floor(0.932) // gives 0
But this throws up another problem. Number between 0.9 and 1.0 will all be rounded down (after
multiplying with 10) to 9!
The solution lies in multiplying the random number generated by random() with 11 - one number
more than the range.
The code above generates a random number between 5 and 10. Just to prove that this works
beautifully click to get a list of 20 random number between 5 and 10
a href="ans31.html" target="_blank">
To store these city names, we can either employ different variables such as city1, city2, city3 ...
or insert these values into an array. Let's see how we make an array.
Each variable in an array begins with the array name followed by a numeric value contained in a
pair of square brackets. This numeric value signifies the Index Number of that variable in the
array. Note, that arrays are zero-indexed, that is, they start at index value 0. Also, we don't need
the var keyword to initialize individual variables of an array.
JavaScript allows us to write the array initialization and assignment statements as one. Thus,
Array values are accessed through their index names. We can use a for loop for this purpose.
Now, don't you see the usefulness of arrays? If we had the values in variables of different names
(even city1, city2...), our alert() statement would be very long.
Values stored in arrays can be changed just like other variable values. Further, you can increase
or decrease the number of items in an array... but that's for laters.
The length of an array is found though its length property. The code below, finds the length of
the array, adds 50 to each value and displays the result in an alert box.
var num = new Array(200, 400, 300, 250, 670, 430, 220, 870, 30);
var l = num.length
var msg = "";
for (x = 0; x < l; x++)
{
num[x] = num[x] + 50;
msg = msg + num[x]+ "\n";
}
alert(msg);
Click here for the result.
After initializing the array num and asigning values to it, we find its length and store the value in
variable l. The variable is then used in a for loop where each array value is incremented by 50.
Lastly, you can mix the data types in an array which means that in a single array, some variables
can contain string while the other might contain numeric data and JavaScript wouldn't complain!
Possible Answers
1. Arrays are initialized using the new operator and the Array() construct.
2. var names = new Array();
3. var marks = new Array();
4. Array values can be accessed using loops. The for is frequently used for this purpose.
5. Yes, array values can be changed.
6. JavaScript is a loosely typed language and allows for various data types in a single array.
7.
8. var n = new Array();
9. var t = 10;
10. for (var x = 0; x < 9; x++)
11. {
12. t = t * (x + 1);
13. n[x] = t;
14. }
15. alert(n);
1. Initializing an array
2. Storing the text strings in that array
3. Finding the length of this array
4. Using the Math.random() to generate a random number
5. Using the randomly generated number as index for retrieving a text string from the array.
6. Displaying the text through an alert() box or document.write()
var text_st = new Array("String1", "String2", "String3",
"String4", "String5", "String6", "String7", "String8",
"String9", "String10");
var l = text_st.length;
alert(text_st[rnd_no]);
Thus, we first create our array and add elemnts to it - 10 in this case. To find the number of array
elements, we employ the ARRAY_NAME.length property and store the value in a variable. The
JavaScript Math.round() gets us a random number between 0.0 and 1.0 which we then multiply
with the array length value. Lastly, the Math.floor() method rounds down the random floating
point (decimal) number to an integer. This integer serves as the index number of the array and
we display our randomly generated text.
Note: Array are zero-indexed, thus, we can use the value of variable l (length of the array)
directly because we are using floor() to round down to an integer.
1. No assignments here.
1. Initializing an array
2. Storing the image file names in that array
3. Finding the length of this array
4. Using the Math.random() to generate a random number
5. Using the randomly generated number as index for retrieving an image file name from
the array.
6. Displaying the image.
var l = img_name.length;
document.r_img.src = img_name[rnd_no];
In th code above, we have JavaScript array containing 6 images. The array length found from
length is, thus, 6 - img_name[0] would be "purple.gif", img_name[1] would be "red.gif" and so
on. We then use the Math.round() to get a random number, multiply it with the array length and
round it up using Math.floor().
Note: Array are zero-indexed, so the last element in the array will the length of the array minus
1. However, since we are employing floor() to get an integer, we can use the value from
ARRAY_NAME.length directly.
You can also use the id attribute of the image tag instead of name; as:
var l = img_name.length;
document.getElementById("randomimage").src = img_name[rnd_no];