A typical question asked in "History of JavaScript" classes where the teacher mistakenly believes they are teaching programming.


The student is asked to produce a triangle made up of asterisks. A number is entered and that number of asterisks makes up the base of the triangle with each preceding line having one fewer asterisk and with the asterisks centred over the following line.

Historical Answer:

var x = parseInt(prompt("Your value",""));
var A= "";
var B=[" "];
for (i=0; i<x; i++) B[i+1]=B[i]+" ";
for (i=0; i<x; i++) {
A = A+"*";
document.write("<br>"+B[x-i] + A) }

The historical answer here is fairly simple and relies on adding non-breaking spaces and line breaks into the HTML (neither of which is semantic in this instance) in order to produce the desired output.

JavaScript Answer:

While this modern answer looks like it involves a lot more code, the only JavaScript code written specifically for this problem is the triangle() function. This makes an obvious question for testing knowledge of the Document Object Model (which is done at a completely different stage in a modern JavaScript course from where the question is used in a history course) and so all of the code except that in the triangle function can be supplied to the student with them just being asked to complete that function (all of the other code are basically library functions you'd use in lots of your scripts). Here we assume that the * is the same size as a lowercase x and so can add half an ex to the left padding for each of the following rows that is yet to be generated in order to get the indentation closer to being right than in the historical solution.

In a real world situation rather than using non-breaking spaces or left padding you'd simply use text-align:center in the CSS.


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow