Here is some practice just running Javascript code. Let’s start by copying and pasting the code below into jsfiddle. Since this is html code (<html> tags), then you will paste it into the upper HTML window. After you run the program, try changing something and running it again. Does it do what you expect? Remember, it may not work at all. In which case, copy the code again from this page and try it again. Here is the first example: (Non-bold text)
<html>
<head>
<script type=”text/javascript”>
var c = 0;
function count() {
// This program will add 1 to c for each click and display it
c = c + 1;
alert(c);
}
</script>
</head>
<body>
<input type=”button” value=”Click to count” onclick=”count();”>
</body>
</html>
A SECOND EXAMPLE: NOTE THIS ONE DOES NOT HAVE THE HTML TAGS. COPY IT INTO THE LOWER JAVASCRIPT WINDOW AND RUN IT. NOTE ALSO, I HAVE BEEN GETTING UNPREDICTABLE RESULTS WITH JSFIDDLE. IF IT DOES NOT WORK, COME BACK TO ME WITH QUESTIONS. PROBABLY NOT YOUR FAULT, BUT JSFIDDLE IS A GOOD LEARNING TOOL WHEN IT WORKS PROPERLY
var stuff = prompt(“enter a phrase”,””);
document.write(stuff + “<br>”);
for (i=stuff.length; i>=0; i–)
document.write(stuff.charAt(i));
NOW TRY RUNNING BOTH EXAMPLES, NOT THROUGH JSFIDDLE, BUT BY COPYING THEM TO NOTEPAD AND SAVING THEM AS AN HTML FILE. REMEMBER, HOWEVER, YOU NEED TO FIRST MAKE THEM INTO AN HTML FILE. DO THIS BY ADDING ‘<html>’ AND ‘<script type = “text/javascript”>’ BEFORE THE TEXT, AND ‘</script> AND ‘</html>’ AFTER THE TEXT. FOR EXAMPLE, THE LAST PROGRAM YOU RAN IN JSFIDDLE WOULD LOOK LIKE:
<html>
<script type = “text/javascript”>
var stuff = prompt(“enter a phrase”,””);
document.write(stuff + “<br>”);
for (i=stuff.length; i>=0; i–)
document.write(stuff.charAt(i));
</script>
</html>
LETS RETURN TO JSFIDDLE AND RUN A COUPLE OF OTHER JAVASCRIPT PROGRAMS. ONE OF YOUR COMPETENCIES WILL BE TO ‘THINK LIKE A COMPUTER’ AND PREDICT THE OUTPUT OF A PROGRAM. I WILL GIVE YOU A PROGRAM LIKE THE ONE BELOW AND YOU WILL TELL ME EXACTLY WHAT IT PRINTS OUT. COPY THIS PROGRAM TO JSFIDDLE.NET AND SEE WHAT THE OUTPUT IS. CHANGE THE VALUE OF THE FIRST 3 VARIABLES (a,b, OR c). RUN IT AGAIN. REMEMBER, ANY CHANGE MIGHT BREAK IT, SO RETURN TO THE ORIGINAL CODE AND TRY AGAIN. TRY RUNNING BOTH AS AN HTML FILE.
var a=1, b=7, c=9;
while ( a < 5 )
{
if (a>2)
{
document.writeln(“One” + a + “<br>”);
}
if (b>a)
{
while ( b > 2)
{
document.writeln(“Two” + b + “<br>”);
if ( b == 3)
{
document.writeln(“Three” + b + “<br>”);
b=b-1;
}
b=b-2;
}
}
if (a==3)
{
b = 6;
}
document.writeln(“Four” + a + “<br>”);
a = a + 1
}
HERE IS A SECOND EXAMPLE. AGAIN, PLAY AND TWEAK
var a=1, b=7, c=9;
if (a>3)
{
while (c>0)
{
document.write(“nope” + c + “<br>”);
c=c-3
}
}
while ( c > 1)
{
document.write(“inside” + c + “<br>”);
if (a<5)
{
if (b>2)
{
while (b!=4)
{
document.write(“go for” + b + “<br>”);
b=b-1
}
document.write(“more” + a + “<br>”);
}
document.write(“yes” + b + “<br>”);
}
document.write(“again” + c + “<br>”);
c=c-2;
}