JavaScript Tutorial - 1

This tutorial assumes that you know basic HTML - for example:

<html> <head> <title>Hello World</title> </head> <body> <h1>Hello World</h1> </body> </html> We could also produce the same effect using JavaScript - it would look like this: <html> <head> <title>Hello World</title> </head> <body> <script> document.write("<h1>Hello World</h1>") </script> </body> </html> 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:

<html> <head> <title>Hello World 50 times</title> </head> <body> <script> for (var n=1; n<51; n++) { document.write("<h1>Hello World</h1>") } </script> </body> </html> 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: <html> <head> <title>Hello World 50 times</title> </head> <body> <script> for (var n=1; n<51; n++) { document.write(n) document.write("<h1>Hello World</h1>") } </script> </body> </html> 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("<h1>Hello World</h1>") }
  • 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

HOME Table of Contents Previous Next