This tutorial assumes that you know basic HTML - for example:
Hello World
Hello World
We could also produce the same effect using JavaScript - it would look like this:
Hello World
You may well ask "Why bother?" since the code is more complex and yet the result is identical.
Ah ... but suppose we wanted to write Hello World 50 times?
I know ... why would you want to? ... but bear with me :o)
To do this in HTML, you would have to reproduce the Hello World line 49 times.
JavaScript lets us use a magic shortcut called a
loop.
I'll explain the parts in a moment but just try this first:
Hello World 50 times
Ok, let's study those amazing three lines of JavaScript.
The n names a storage box.
(It's official title is a variable.)
You can see what is in this box by asking JavaScript to tell you - try this:
Hello World 50 times
Task 1: What happens if you write document.write("n")
instead of what I used?
Check.
This is an enormously important distinction to master:
If you want to display the letter a, you enclose it in "quotes".
If you want to display what's in a storage box called a, DON'T use quotes.
Task 2: Change the above program so that the numbers are bolded.
Check.
Back to those three lines of JavaScript:
for (var n=1; n<51; n++) {
document.write("Hello World
")
}
- The word
for
tells JavaScript that this is the start of a
loop.
- The stuff in the
(round brackets)
tells JavaScript all about the loop.
- We tell JavaScript that we want to use a storage box called
n
with the word
var.
- n=1
means put a one in the box. Change the "1" to "40" and see what happens.
- n<51
means keep looping as long as n is less than 51. Change the "51" to "41" and see what happens.
- n++
means add ONE to what's in box n.
- The
{curly brackets}
package the instructions that have to be looped through.
Task 3: Use JavaScript to write the numbers 1 to 10 across the page.
Make sure your numbers are separated by a space.
Check.
Challenge 1: Use JavaScript to produce this pattern
(there are ten rows - note that your answer should be able to produce 1000 rows just as easily):
M
MM
MMM
MMMM
MMMMM
MMMMMM
MMMMMMM
MMMMMMMM
MMMMMMMMM
MMMMMMMMMM