Chapter 2 lab Chapter 3 lab Chapter 4 lab Chapter 5 lab Chapter 6 lab Chapter 7 lab Chapter 8 lab Chapter 9 lab Chapter 10 lab Chapter 12 lab Chapter 13 lab
Chapter 5 · Lab

Lab 4: The Basics of JavaScript

A hands-on JavaScript lab: output and variables, external scripts, alert/confirm/prompt dialogs, switch and loops, the Math object, and drawing on an HTML5 canvas.

Learning outcomes

  • Create simple scripts that include input and output statements
  • Use arithmetic, relational and equality operators
  • Write counter-controlled and sentinel-controlled repetition (for, while, do...while)
  • Write functions and pass information between them
  • Use JavaScript built-in functions such as Math, String and Date
  • Write programs using HTML5 Canvas and JavaScript

Your progress

Tasks completed 0/9

Log in to save your lab progress. Log in

1

Task 1 — Your first JavaScript page

JavaScript is included in an HTML document using the <script> tag. The standard command for writing output to a page is document.write() — document is a built-in object representing the HTML document, and write() is a method of that object.

  1. Run the code and look at the output.
  2. Declare another variable and display it with document.write().
  3. Notice that // starts a JavaScript comment.

Code

basic.html
<h1>My First JavaScript Page</h1>
script.js
// Output statement
document.write("Welcome to my website.<br>");

// Declare variables and display them
var title = "Faizal's Site";
document.write("This is " + title + ".");

Try it

basic.html
script.js
2

Task 2 — Using an external JavaScript

Internal scripts apply only to the document in which they were created. To run the same script on several pages, put it in an external .js file and link it with the src attribute.

<head>
  <script src="external.js"></script>
</head>

The external script must not contain the <script> tag. In this editor, the JavaScript pane plays the role of external.js.

Code

basic.html
<h1>Using an External JavaScript</h1>
external.js
// The content of external.js (no <script> tag!)
var title = "Faizal's Site";
document.write("This is " + title + ".");

Try it

basic.html
external.js
3

Task 3 — Alert, confirm & prompt

The alert, confirm and prompt message boxes are methods of the window object. Because window is at the top of the object hierarchy, you can call them without the full name — but using the full name reminds you which object they belong to.

  • window.alert() — shows a message; the user clicks OK.
  • window.confirm() — OK returns true, Cancel returns false.
  • window.prompt() — asks the user to type a value.

Code

dialogbox.html
<h1>Dialog Boxes</h1>
<button onclick="showAlert()">Show Alert</button>
<button onclick="showConfirm()">Confirm</button>
<button onclick="showPrompt()">Prompt</button>
<p id="result"></p>
dialogbox.js
function showAlert() {
  window.alert("Thank you for your submission.");
}

function showConfirm() {
  var answer = window.confirm("Are you sure you want to proceed?");
  document.getElementById("result").innerHTML =
    answer ? "You clicked OK." : "You clicked Cancel.";
}

function showPrompt() {
  var name = window.prompt("Enter your name:", "");
  if (name !== null) {
    document.getElementById("result").innerHTML = "Hello, " + name + "!";
  }
}

Try it

dialogbox.html
dialogbox.js
4

Task 4 — Switch...case lucky draw

The switch statement selects one of several blocks of code to run based on a value. parseInt() converts the string returned by prompt() into an integer.

  1. Click the button and enter a number between 1 and 3.
  2. Try an invalid number to see the default case.

Code

switchcase.html
<h1>Lucky Draw</h1>
<button onclick="drawPrize()">Draw a prize</button>
<div id="output"></div>
switchcase.js
function drawPrize() {
  var number = prompt("Enter a number between 1 and 3 to collect your prize.", "0");
  var output = document.getElementById("output");

  switch (parseInt(number)) {
    case 1:
      output.innerHTML = "You have won yourself an iPhone!";
      break;
    case 2:
      output.innerHTML = "You have won yourself an iPod!";
      break;
    case 3:
      output.innerHTML = "You have won yourself an iPad!";
      break;
    default:
      output.innerHTML = "Sorry, wrong value.";
  }
}

Try it

switchcase.html
switchcase.js
5

Task 5 — for loop: temperature converter

The for loop is used when you know in advance how many times the script should repeat. This converter uses the formula F = (C × 9 / 5) + 32.

Exercise: change the code so the table converts the same values but from Fahrenheit to Celsius (C = (F - 32) × 5 / 9).

Code

loopfor.html
<h1>Celsius to Fahrenheit</h1>
<div id="output"></div>
loopfor.js
var output = "";

for (var celsius = 0; celsius <= 100; celsius += 10) {
  var fahrenheit = (celsius * 9 / 5) + 32;
  output += celsius + " C = " + fahrenheit + " F<br>";
}

document.getElementById("output").innerHTML = output;

Try it

loopfor.html
loopfor.js
6

Task 6 — while / do...while loop

The while loop repeats until a condition becomes true. In this quiz the loop keeps asking until the correct answer is given.

  1. Click the button and answer the question.
  2. Try a wrong answer first — the loop keeps asking.
  3. Exercise: rewrite it using a do...while loop.

Code

loopwhile.html
<h1>Multiplication Quiz</h1>
<button onclick="startQuiz()">Start quiz</button>
<p id="output"></p>
loopwhile.js
function startQuiz() {
  var x = prompt("What is 5 x 5?", "");

  while (parseInt(x) !== 25) {
    alert("Wrong answer");
    x = prompt("What is 5 x 5?", "");
  }

  document.getElementById("output").innerHTML = "Correct, the answer is 25.";
}

Try it

loopwhile.html
loopwhile.js
7

Task 7 — JavaScript Math built-in functions

JavaScript's built-in Math object provides many functions: abs(), ceil(), floor(), log(), max(), min(), pow(), random(), round(), sqrt() and trigonometric methods.

This example uses Math.pow() to calculate the volume of a cube from the length of its side.

Code

math.html
<h1>Math functions</h1>
<div id="output"></div>
math.js
var input = prompt("Enter the side of the cube to calculate its volume", "3");
var side = input ? parseInt(input) : 3;

var output = "Side: " + side + "<br>";
output += "Volume (pow): " + Math.pow(side, 3) + "<br>";
output += "sqrt(81): " + Math.sqrt(81) + "<br>";
output += "ceil(4.2): " + Math.ceil(4.2) + "<br>";
output += "floor(4.8): " + Math.floor(4.8) + "<br>";
output += "round(4.5): " + Math.round(4.5) + "<br>";
output += "abs(-7): " + Math.abs(-7) + "<br>";
output += "max(3, 9): " + Math.max(3, 9) + "<br>";
output += "random(): " + Math.random().toFixed(4) + "<br>";

document.getElementById("output").innerHTML = output;

Try it

math.html
math.js
8

Task 8 — HTML5 Canvas: rectangles & paths

The <canvas> element gives you a powerful way to draw graphics with JavaScript. The canvas is initially blank; a script must get the rendering context with getContext('2d') before drawing.

  • fillRect(x, y, w, h) — draws a filled rectangle.
  • strokeRect(x, y, w, h) — draws a rectangular outline.
  • clearRect(x, y, w, h) — makes a rectangular area transparent.
  • beginPath(), arc(), fill() — draw paths such as circles.

Code

shapes.html
<h1>Canvas &mdash; rectangles &amp; paths</h1>
<canvas id="mycanvas" width="200" height="200"></canvas>
shapes.css
canvas {
  border: 1px solid #dfe6ee;
  border-radius: 10px;
}
shapes.js
var canvas = document.getElementById("mycanvas");

if (canvas.getContext) {
  var ctx = canvas.getContext("2d");

  // Filled rectangle
  ctx.fillStyle = "#2563eb";
  ctx.fillRect(10, 10, 80, 80);

  // Clear a rectangular area inside it
  ctx.clearRect(20, 20, 40, 40);

  // Rectangle outline
  ctx.strokeStyle = "#0ea5a4";
  ctx.strokeRect(100, 100, 80, 80);

  // A circular path
  ctx.beginPath();
  ctx.arc(150, 50, 30, 0, Math.PI * 2, false);
  ctx.fillStyle = "#f59e0b";
  ctx.fill();
} else {
  alert("You need a browser that supports canvas.");
}

Try it

shapes.html
shapes.css
shapes.js
9

Task 9 — Canvas: lines, text & Bezier curves

Paths are drawn with beginPath(), moveTo(), lineTo() and closePath(), then fill() or stroke().

  • lineTo(x, y) — adds a point connected by a straight line.
  • bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y) — draws a cubic Bezier curve.
  • fillText(text, x, y) — draws filled text.
  • drawImage(image, x, y) — draws an image onto the canvas.

Code

curves.html
<h1>Canvas &mdash; lines, text &amp; curves</h1>
<canvas id="mycanvas" width="240" height="210"></canvas>
curves.css
canvas {
  border: 1px solid #dfe6ee;
  border-radius: 10px;
}
curves.js
var canvas = document.getElementById("mycanvas");
var ctx = canvas.getContext("2d");

// Filled triangle from straight lines
ctx.beginPath();
ctx.moveTo(20, 20);
ctx.lineTo(120, 20);
ctx.lineTo(20, 120);
ctx.closePath();
ctx.fillStyle = "#2563eb";
ctx.fill();

// Stroked rectangle from straight lines
ctx.beginPath();
ctx.moveTo(140, 20);
ctx.lineTo(220, 20);
ctx.lineTo(220, 100);
ctx.lineTo(140, 100);
ctx.closePath();
ctx.strokeStyle = "#0ea5a4";
ctx.stroke();

// Cubic Bezier curve
ctx.beginPath();
ctx.moveTo(20, 170);
ctx.bezierCurveTo(80, 100, 160, 240, 220, 170);
ctx.strokeStyle = "#f59e0b";
ctx.lineWidth = 3;
ctx.stroke();

// Text
ctx.font = "italic 20px sans-serif";
ctx.fillStyle = "#0b1f3a";
ctx.fillText("Hello Canvas!", 20, 200);

Try it

curves.html
curves.css
curves.js