Experimental forum for "Technology" discussions (computers, cameras, etc).

Learn to Program: JavaScript

Postby Bob Kuczewski » Thu Sep 02, 2021 2:11 am

Learn to Program: JavaScript

If I were suggesting a beginner computer language 20 or 30 years ago it would be BASIC. At that time, it was widely available and/or already installed (as "QBASIC") on almost all computers of that era. But today, the most widely available computer language is JavaScript. That's because JavaScript is supported by almost all modern web browsers. So it doesn't matter what operating system you're running (Windows, MacOS, or Linux). If you have a modern web browser, you are highly likely to have everything you need to write JavaScript programs.

This is the second computer "language" topic in our "Learn to Program" series (following BBCode). I'll be posting lessons and "exercises" for JavaScript in this topic. Feel free to do the exercises and post your results. Also feel free to post any questions. Mostly, have fun!!
Join a National Hang Gliding Organization: US Hawks at ushawks.org
View my rating at: US Hang Gliding Rating System
Every human at every point in history has an opportunity to choose courage over cowardice. Look around and you will find that opportunity in your own time.
Bob Kuczewski
User avatar
Contributor
Contributor
 
Posts: 8339
Joined: Fri Aug 13, 2010 2:40 pm
Location: San Diego, CA

JavaScript - Getting Started

Postby Bob Kuczewski » Thu Sep 02, 2021 3:08 am

Getting Started

There are 2 relatively easy ways to get started with JavaScript: Web Interface and Local Files. I use both.

Web Interface

The web interface is the quickest and easiest way to get started, but it has some important limitations that we'll discuss later. There are probably a number of web sites that offer a JavaScript learning environment, but I tend to like W3Schools.com. Here's a quote from their JavaScript introduction page:

   https://www.w3schools.com/js/DEFAULT.asp
w3schools.com wrote:JavaScript is the world's most popular programming language.

JavaScript is the programming language of the Web.

JavaScript is easy to learn.

This tutorial will teach you JavaScript from basic to advanced.


At each step in their lessons, they give you some instruction and then give you a chance to "Try it Yourself" as shown here:

W3JS1.png
W3JS1.png (39.5 KiB) Viewed 1874 times

When you click the "Try it Yourself" button. You'll go to a page that shows an editor on the left and the result on the right:

W3JS2.png
W3JS2.png (35.25 KiB) Viewed 1874 times

When you click the "Run" button, their web site will run your code (on the left) and show you the result (on the right). This gives you an easy way to try out any JavaScript that you like. You just have to remember to copy and save your text program when you are done ... otherwise it may be gone when you leave their page.


Local Files

The web interface is extremely convenient for quick testing of code fragments, but local files are much better for serious work. Local files are simply JavaScript and HTML files stored on your own computer. The only downside is finding and using a text editor for plain text files in Windows. For example, you would need to have a way to edit and save the following text to a file named "my_first.html".

<!DOCTYPE html>
<html>
<body>

<h2>My First JavaScript</h2>

<button type="button"
onclick="document.getElementById('demo').innerHTML = Date()">
Click me to display Date and Time.</button>

<p id="demo"></p>

</body>
</html>

If you can do that, then you can use the "local files" approach. Don't worry about what that all means. We'll get to that later.

You can test your program by opening that HTML file with your web browser. The web browser will run your program and show you any results.


If you can get either method to work, then you're all set to continue learning to program with JavaScript.

Reference Material

    Javascript.info

 
Attachments
show_date_time.htm.zip
(344 Bytes) Downloaded 5 times
Join a National Hang Gliding Organization: US Hawks at ushawks.org
View my rating at: US Hang Gliding Rating System
Every human at every point in history has an opportunity to choose courage over cowardice. Look around and you will find that opportunity in your own time.
Bob Kuczewski
User avatar
Contributor
Contributor
 
Posts: 8339
Joined: Fri Aug 13, 2010 2:40 pm
Location: San Diego, CA

Learn to Program: JavaScript HTML and JavaScript

Postby Bob Kuczewski » Sun Jan 16, 2022 4:53 pm

If that previous program worked (using either the web interface or local files), then we can begin to work through a simple program.

Let's start with HTML itself first. HTML stands for "Hyper Text Markup Language", and it's very similar to our own BBCode tags. The primary difference is that HTML uses angle brackets ( < and > ) instead of the square brackets ( [ and ] ) that we use in BBCode. For example, here's a comparison between BBCode and HTML:




FeatureBBCodeHTMLExample
Bold[b] and [/b]<b> and </b>Bold
Italic[i] and [/i]<i> and </i>Italic
Underline[u] and [/u]<u> and </u>Underline


But "proper" HTML also has a number of other kinds of tags that we don't need in BBCode because BBCode is generally written within an existing document (the page where the post appears). So while a forum post can just start out with plain text, a proper HTML web page needs a few more tags. Here's a pretty basic HTML web page:

<!DOCTYPE html>
<html>
<body>
Hello from a web page!!
</body>
</html>


Just as with BBCode, you'll notice that our "tags" are mostly grouped in pairs. There's an <html> tag and a </html> tag. There's a <body> tag and a </body> tag. The only tag that's not paired is the first line (<!DOCTYPE html>) which declares the document type. In the very early days, this "DOCTYPE" line wasn't used much at all. But as HTML began to have many different variations, the "DOCTYPE" line became a way to let browsers know which variation was being used.

So our simple HTML document contains:

1. A DOCTYPE line
2. A pair of "html" tags ( <html> and </html> )
3. A pair of "body" tags ( <body> and </body> )
4. A line of text that says "Hello from a web page!!"


If you display that web page in a browser (either via the web interface or as a file), it will look like this:

Hello from a web page!!

In other words, all of the DOCTYPE, and <html> and <body> stuff doesn't show up at all. That part of the code is just helping to set up the page. The actual content is what appears between the <body> and </body> tags. Let's emphasize that by "graying out" all the stuff that's used to set up the page:

<!DOCTYPE html>
<html>
<body>

Hello from a web page!!
</body>
</html>


Before we get into JavaScript itself, there's just one more thing to mention about HTML - HTML totally ignores what we call "redundant white space" in our text. In other words two spaces will be shown as just one space. 100 spaces will just show up as 1 space. Ten carriage returns (new lines) will show up as just 1 space. So the following 2 documents will show up exactly the same when viewed by a web browser:

  Document 1:
<!DOCTYPE html>
<html>
<body>

Hello from a web page!!
</body>
</html>

  Document 2:
<!DOCTYPE html>
<html>
<body>

        Hello
from          a
                 web                  page!!
</body>
</html>

They will both show up as before:

Hello from a web page!!


However, if you want to force a line break, you can use the <br/> tag wherever you want the line to break as shown here:

<!DOCTYPE html>
<html>
<body>

Once upon a midnight dreary,<br/>
while I pondered, weak and weary,<br/>
Over many a quaint and curious<br/>
volume of forgotten lore ...<br/>
</body>
</html>


O.K., that's all the HTML we need to know to get started with JavaScript. We can insert our JavaScript into that basic template as follows:

<!DOCTYPE html>
<html>
<body>

<script>
document.write("Hello from JavaScript!!");
</script>
</body>
</html>


You'll notice that I added a <script> tag and a </script> tag. Those aren't JavaScript, but they tell the web browser that what's in between is JavaScript. And what's in between those JavaScript tags is this:

         document.write("Hello from JavaScript!!");

That's the actual JavaScript. That one line of JavaScript tells your web browser to write the text string "Hello from JavaScript!!" into the document (the web page). If you view that HTML in a web browser it will show up as this:

Hello from JavaScript!!


Now that may seem like a lot of work to print a single line to a web page, and if that's all that JavaScript could do, then it wouldn't be worth the trouble. But that's not all that JavaScript can do. For example, if you've looked at the Glider Designer page (https://ushawks.org/designer/), that program was written in JavaScript. Here's the picture that it can make from a few simple measurements of a glider:

Predator_Model.png
Predator_Model.png (30.26 KiB) Viewed 1764 times

Now that Glider program is pretty complicated, and I wouldn't use it as an introductory example. But here's a much simpler program :

<!DOCTYPE html>
<html>
<body>
<table border="1">
<script>

for (i=1; i<=16; i++) {
document.write("<tr>");
for (j=1; j<=16; j++) {
document.write("<td>" + (i*j) + "</td>");
}
document.write("</tr>");
}
</script>
</table>
</body>
</html>


What does that program do? Well, you could copy that text, put it into a file named "mt.html" and open it with your web browser to find out (and I hope you will). Here's what you're likely to see:

MT.png
MT.png (103.05 KiB) Viewed 1765 times

Do you recognize it? It's the multiplication table of all numbers from 1 to 16. In other words, this little bit of JavaScript generated that entire table:

for (i=1; i<=16; i++) {
document.write("<tr>");
for (j=1; j<=16; j++) {
document.write("<td>" + (i*j) + "</td>");
}
document.write("</tr>");
}

That's the power of programming. Programmers learn to tell the computer what to do, and then the computer does all the work.

This post is actually getting a bit ahead of itself because I've shown a lot of programming code without explaining it. But at this point, all you need to try to do is copy a few of these programs into either the web interface or the file interface and try them out. The details will be explained as we go. For now, the easiest thing you can do is to copy that last FULL example and paste it into the left window at this web site:

        https://www.w3schools.com/js/tryit.asp?filename=tryjs_default

It should look like this (after you've clicked the "  Run  " button):

W3SchoolsExample.png
W3SchoolsExample.png (180.66 KiB) Viewed 1764 times

As a final review, watch this animated slide for a few rounds until you are comfortable with each section. Don't worry about the JavaScript yet. We'll get to that later. Just be sure that you can make it run and get the table above either from a file on your computer or from the web interface at www.w3schools.com. Note that if you use the w3schools web site, you'll have to delete whatever program is already showing in the left side of that page before you can copy and paste this program into it and run it.

JavaScript_MT_Example.gif
JavaScript_MT_Example.gif (110.59 KiB) Viewed 1763 times



Exercise 1 (Run a JavaScript Program):

Either:

1. Copy this program (below) into a file named "MT.html" and open it in a web browser.

       - or -

2. Copy this program (below) into www.w3schools.com and run it.

Here's the program for you to select, copy, and paste:

<!DOCTYPE html>
<html>
<body>
<table border="1">
<script>

for (i=1; i<=16; i++) {
document.write("<tr>");
for (j=1; j<=16; j++) {
document.write("<td>" + (i*j) + "</td>");
}
document.write("</tr>");
}
</script>
</table>
</body>
</html>


All of the files included in this post are attached as ".zip" files below. You should be able to download them, unzip them, and run them.
 
Attachments
hello_html.htm.zip
(225 Bytes) Downloaded 6 times
hello_line_breaks.htm.zip
(321 Bytes) Downloaded 6 times
hello_javascript.htm.zip
(267 Bytes) Downloaded 4 times
multiplication_table.htm.zip
(346 Bytes) Downloaded 6 times
Join a National Hang Gliding Organization: US Hawks at ushawks.org
View my rating at: US Hang Gliding Rating System
Every human at every point in history has an opportunity to choose courage over cowardice. Look around and you will find that opportunity in your own time.
Bob Kuczewski
User avatar
Contributor
Contributor
 
Posts: 8339
Joined: Fri Aug 13, 2010 2:40 pm
Location: San Diego, CA

Re: Learn to Program: JavaScript

Postby Bob Kuczewski » Thu Jan 20, 2022 12:53 am

OK, now we're ready to actually write a JavaScript program to do something useful. Let's say that we want to write a program that gives us a random number whenever we press a button. That program might operate as follows:

Random number is: ?


Now go ahead and click on that button. Do you see a long random number like 0.8934664393588754? Click it again. Do you see a different random number?

That was done with a pretty simple little JavaScript program. Let's look at that program:

<!DOCTYPE html>
<html>
<body>
<button
type="button"
onclick="document.getElementById('rn1').innerHTML=Math.random()"
>
Click to display a random number.
</button>
<p>Random number is: <span id="rn1">?</span></p>
</body>
</html>


Let's start by "graying out" the boiler plate stuff that we've seen before:

<!DOCTYPE html>
<html>
<body>

<button
type="button"
onclick="document.getElementById('rn1').innerHTML=Math.random()"
>
Click to display a random number.
</button>
<p>Random number is: <span id="rn1">?</span></p>
</body>
</html>


Now we can remove the grayed out code to focus on what's left:

<button
type="button"
onclick="document.getElementById('rn1').innerHTML=Math.random()"
>
Click to display a random number.
</button>
<p>Random number is: <span id="rn1">?</span></p>


Well, that's a little better, but it's still a lot to chew on. So let's break it down a little further. You may remember from BBCode (or the earlier HTML table above) that most tags come in pairs. They are like book ends around something else. If you look at that code you'll see 3 "book ends" of HTML tags. There's a <button> and a </button>, a <p> and a </p>, and a <span> and a </span>. If we just look at the tags and the text without the parameters inside the tags, it looks like this:


<button>
Click to display a random number.
</button>
<p>Random number is: <span>?</span></p>


Now that's something we can start to understand. The <button> and </button> tags make a button that's labeled with "Click to display a random number.". Similarly (but less obviously) the <p> and </p> tags make a paragraph containing the text "Random number is: ?". That's what we see when the program is first displayed:

RandomNumber.png
RandomNumber.png (18.54 KiB) Viewed 1741 times

That seems reasonable, but what about the <span> and </span> tags around the question mark?

The <span> and </span> tags are there to give an identification name to the question mark itself. Remember that before we simplified things, that "span" section looked like this:

        <span id="rn1">?</span>

You can see that there's an "id" parameter inside the opening "<span>" tag, and the "id" is set to "rn1". So if we want to change that question mark to something else (like a random number) we can change it by its "id" value.

Let's review what we have so far. We have a button that contains the label "Click to display a random number.", and we have a paragraph that contains the text "Random number is: ?". We also have a label on the question mark named "rn1".

So the only thing left to do is make the button put a random number where the question mark is. That's where the JavaScript comes in. Do you remember what the <button> tag looked like before we simplified It? Here it is from our earlier version:

<button
type="button"
onclick="document.getElementById('rn1').innerHTML=Math.random()"
>
Click to display a random number.
</button>


So the opening button tag wasn't just <button>. It was:

<button
type="button"
onclick="document.getElementById('rn1').innerHTML=Math.random()"
>


In other words, the opening <button> tag contained these two parameters:

type="button"
onclick="document.getElementById('rn1').innerHTML=Math.random()"


The first parameter (setting the type to "button") is pretty obvious, but the "onclick" parameter needs some explanation. The "onclick" parameter defines what will be done when the button is clicked. In this case, when that button is clicked the web browser will execute the JavaScript:

        document.getElementById('rn1').innerHTML=Math.random()"

Aha!! That's the "secret sauce"!! That's a line of JavaScript that tells the computer to go to the document (web page), get the thing ("Element") with an ID of "rn1", and set its "inner HTML" to a random number. So every time you click that button, the computer will follow those JavaScript instructions and put a new random number into the "span" element with the ID of "rn1".

So there's an actually useful program that you can operate by clicking a button. Every click will give you a new random number. You could use that to play a game or generate some numbers for a very secure password. You could even use it as a primitive fortune teller: If the first digit is even, then I should fly today, but if It's odd, then I should fly tomorrow. Who could argue with that?!?

Have fun!! :wave:

 
Attachments
random_number.htm.zip
(349 Bytes) Downloaded 5 times
Join a National Hang Gliding Organization: US Hawks at ushawks.org
View my rating at: US Hang Gliding Rating System
Every human at every point in history has an opportunity to choose courage over cowardice. Look around and you will find that opportunity in your own time.
Bob Kuczewski
User avatar
Contributor
Contributor
 
Posts: 8339
Joined: Fri Aug 13, 2010 2:40 pm
Location: San Diego, CA

Re: Learn to Program: JavaScript

Postby Bob Kuczewski » Thu Jan 20, 2022 8:04 am

This is a fun variation of the previous program to roll some random virtual dice. This program isn't intended to be fully understood yet, but it demonstrates a more complete and potentially useful program.

Each button below will roll some number of virtual dice and show the results beside the button. You can push each button as many times as you like, and you'll get a different random roll of the dice for each one.












Here's what the code for the "Roll 8" button might look like (the forum version is slightly different to handle parameters):

<!DOCTYPE html>
<html>
<body>
<script>
// These are the UniCode values for the 6 dice faces
faces = [ "&#9856;", "&#9857;", "&#9858;",
"&#9859;", "&#9860;", "&#9861;" ];

// This function runs when the button is pushed
function roll(n) {
rs = ""; // Set the roll string (rs) variable to an empty string
for (i=0; i<parseInt(n); i++) { // Loop over each die to show
d = 6 * Math.random(); // Pick a random number up to 6
d = Math.floor(d); // Turn it into an integer 0 through 5
rs = rs + " " + faces[d]; // Add the face to the roll string
}
// Put the roll string into the HTML element with id of "dice1"
document.getElementById('dice1').innerHTML = rs;
}
</script>
<button type="button" onclick="roll('8')">Roll 8</button>
<p><span id="dice1"></span></p>
</body>
</html>

And here's a picture of one set of rolls (your dice may use a different font):

Dice_Rolls.png
Dice_Rolls.png (43.41 KiB) Viewed 1734 times

 
Attachments
roll_8_dice.htm.zip
(647 Bytes) Downloaded 7 times
Join a National Hang Gliding Organization: US Hawks at ushawks.org
View my rating at: US Hang Gliding Rating System
Every human at every point in history has an opportunity to choose courage over cowardice. Look around and you will find that opportunity in your own time.
Bob Kuczewski
User avatar
Contributor
Contributor
 
Posts: 8339
Joined: Fri Aug 13, 2010 2:40 pm
Location: San Diego, CA

Re: Learn to Program: JavaScript

Postby Bob Kuczewski » Fri Jan 21, 2022 11:56 am

By the way, here's an example of rolling 400 dice at once. Just push the button to roll and re-roll all 400 at once. This is the power of computer programming.



 
Attachments
roll_400_dice.htm.zip
(653 Bytes) Downloaded 7 times
Join a National Hang Gliding Organization: US Hawks at ushawks.org
View my rating at: US Hang Gliding Rating System
Every human at every point in history has an opportunity to choose courage over cowardice. Look around and you will find that opportunity in your own time.
Bob Kuczewski
User avatar
Contributor
Contributor
 
Posts: 8339
Joined: Fri Aug 13, 2010 2:40 pm
Location: San Diego, CA

Re: Learn to Program: JavaScript

Postby Bob Kuczewski » Sat Sep 07, 2024 3:31 pm

Javascript inside HTML

The previous examples all used Javascript inside of an HTML document. This is a common case, and it can lead to some confusion about which "language" is being used in which part of a given document.

HTML stands for "HyperText Markup Language", and it was the original "language" of the World Wide Web. HTML is really a way to describe a web page in a way that helps a browser to display it. It's mostly full of angle brackets ("<" and ">") that define "tags" to let the browser know how different sections should be displayed. For example, to make something bold, just surround it with "<b>" and "</b>". To define a paragraph of text, just surround the text with "<p>" and "</p>". To build a table, use "<table>" and "</table>" to define the table itself. Then use "<tr>" and "</tr>" to define each table row within the table, and use "<td>" and "</td>" to define each item ("table data") within each row. So HTML is easy to spot because it's full of angle brackets. Here's a small HTML page that displays a table:

<html>
<body>
<table>
<tr> <td> <b>x</b> </td> <td> <b>x^2</b> </td> <td> <b>x^3</b> </td>
<tr> <td> 1 </td> <td> 1 </td> <td> 1 </td>
<tr> <td> 2 </td> <td> 4 </td> <td> 8 </td>
<tr> <td> 3 </td> <td> 9 </td> <td> 27 </td>
<tr> <td> 4 </td> <td> 16 </td> <td> 64 </td>
<tr> <td> 5 </td> <td> 25 </td> <td> 125 </td>
<tr> <td> 6 </td> <td> 36 </td> <td> 216 </td>
</table>
</body>
</html>

It's pretty easy to see all the angle brackets in HTML!

While HTML is a great "language" for describing the layout of a page, it's not designed to do any actual calculation. This was fine in the early days of the internet, but as time went on, people wanted to do real calculations (scripting) in their web pages. A number of different "languages" were tried, and they had varying degrees of success. Eventually Javascript became the predominant scripting language for web pages, and it is now the most popular language on the web.

Javascript is a fairly traditional computer language, and it looks like a series of instructions with each instruction ending with a semicolon (";"). It also uses curly brackets ("{" and "}") to group instructions. So if you see some text inside a web page with lots of semicolons and curly brackets, then it's very likely to be Javascript. Here's a short section of Javascript code:

faces = [ "&#9856;", "&#9857;", "&#9858;", "&#9859;", "&#9860;", "&#9861;", "&#127922;"  ];
function roll(id,n) {
rs = "";
for (i=0; i<n; i++) {
d = 6 * Math.random();
d = Math.floor(d);
rs = rs + " " + faces[d];
}
document.getElementById(id).innerHTML = rs;
}


Because HTML and Javascript are two separate languages, and because Javascript is usually contained inside an HTML page, the Javascript portions are mostly marked with the HTML tags "<script>" and "</script>". This tells the web browser which parts of the document are normal HTML (the default) and which parts are Javascript.

Here's a complete HTML web page containing Javascript inside the "<script>" and "</script>" tags (the Javascript is red to make it easier to see). Don't worry about the details here, just note where the "script" tags separate the HTML and the Javascript:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Roll the dice</title>
</head>

<body>
<h1>Roll the dice</h1>
<br/>

<script>
faces = [ "&#9856;", "&#9857;", "&#9858;", "&#9859;", "&#9860;", "&#9861;", "&#127922;" ];
function roll(id,n) {
if (n == 0) {
nt = document.getElementById("num_dice").value;
nv = Number(nt);
if (!isNaN(nv)) {
if (nv > 0) {
n = nv;
}
}
} else {
n = parseInt(n);
}
rs = "";
for (i=0; i<n; i++) {
d = 6 * Math.random(); // Six sides on each die
d=Math.floor(d);
rs = rs + " " + faces[d];
}
document.getElementById(id).innerHTML = rs;
}

</script>

<input id="num_dice" value="1" size="5"></input>
<button type="button" onclick="roll('dice_out', '0')">Roll</button>
<br/>
<span id="dice_out" style="font-size:60px;"></span>

</body>
</html>


Again, don't worry about the details in that file, just notice that there are two separate languages (HTML and Javascript). Here's another shorter example from an earlier post.

<!DOCTYPE html>
<html>
<body>
<table border="1">
<script>
for (i=1; i<=16; i++) {
document.write("<tr>");
for (j=1; j<=16; j++) {
document.write("<td>" + (i*j) + "</td>");
}
document.write("</tr>");
}

</script>
</table>
</body>
</html>


And here's about the shortest example possible:

<!DOCTYPE html>
<html>
<body>
<script>
document.write("Hello from JavaScript!!");
</script>
</body>
</html>


In all of these examples, the Javascript is contained inside a single HTML file separated by "script" tags. This is the simplest case for small examples because everything is together in one single file. However, it is possible to store the Javascript in a separate file (or files) that's referenced by the HTML. Most small projects in this topic will follow the single file model used here.
Join a National Hang Gliding Organization: US Hawks at ushawks.org
View my rating at: US Hang Gliding Rating System
Every human at every point in history has an opportunity to choose courage over cowardice. Look around and you will find that opportunity in your own time.
Bob Kuczewski
User avatar
Contributor
Contributor
 
Posts: 8339
Joined: Fri Aug 13, 2010 2:40 pm
Location: San Diego, CA

Re: Learn to Program: JavaScript

Postby Bob Kuczewski » Sat Sep 07, 2024 3:39 pm

Using Javascript to Write to a Web Page

One of the features that makes Javascript so powerful is that it can modify an HTML document that's being displayed by a web browser. A Javascript program can write directly to the HTML document or just change certain parts of the document.

The easiest case is writing directly to the HTML document. That's what we did in the previous example:

<!DOCTYPE html>
<html>
<body>
<script>
document.write ( "Hello from JavaScript!!" );
</script>
</body>
</html>


That program only contains one line of Javascript, and that line writes the entire document at one time using:

document.write ( "Hello from JavaScript!!" );


This simple line is worth exploring. It starts with the word "document". That's a special word in Javascript, and it refers to the entire HTML web page being displayed. The document itself is called an "object" which just means that it contains other data and functions. One of those functions is the "write" function which is represented by "document.write". This is effectively like an instruction that tells the web browser to write a string of text directly into the web page document. The string to write is contained in double quotes inside the parentheses ( "Hello from JavaScript!!" ). If you run that program you'll see "Hello from JavaScript!!" in your browser.

What if we wanted to write two lines to the browser? We could call the "document.write" function twice as in this program:

<!DOCTYPE html>
<html>
<body>
<script>
document.write ( "Hello from JavaScript!!" );
document.write ( "Hello again from JavaScript!!" );
</script>
</body>
</html>


Go ahead and run that program to see what happens. You'll find that the two sentences are "stuck together" as:

      Hello from JavaScript!!Hello again from JavaScript!!

That's because the program is writing to the web browser's document, and the web browser is interpreting it as HTML. And in HTML, all of the text runs together unless specific formatting tags are used. For example, we can add a line break after each sentence by using the HTML "<br/>" (break) tag:

<!DOCTYPE html>
<html>
<body>
<script>
document.write ( "Hello from JavaScript!!<br/>" );
document.write ( "Hello again from JavaScript!!<br/>" );
</script>
</body>
</html>


In fact, we can write all kinds of tags into the document. For example, if we wanted to underline the word "Javascript" in both sentences, we could use the HTML <u> and </u> tags to do so:

<!DOCTYPE html>
<html>
<body>
<script>
document.write ( "Hello from <u>JavaScript</u>!!<br/>" );
document.write ( "Hello again from <u>JavaScript</u>!!<br/>" );
</script>
</body>
</html>


The other way to modify an HTML document is to specify the part to change by an identification code. We can then use the assignment ("=") operator to change that part of the HTML to a new value. For example, this HTML page has 3 paragraphs:

<!DOCTYPE html>
<html>
<body>
<p>This is my first paragraph.</p>
<p>This is my second paragraph.</p>
<p>This is my third paragraph.</p>
</body>
</html>


We can add an "ID" to each paragraph as follows:

<!DOCTYPE html>
<html>
<body>
<p id="p1">This is my first paragraph.</p>
<p id="p2">This is my second paragraph.</p>
<p id="p3">This is my third paragraph.</p>
</body>
</html>


Now we can write some Javascript to use the ID of a chosen paragraph to alter or change its content:

<!DOCTYPE html>
<html>
<body>
<p id="p1">This is my first paragraph.</p>
<p id="p2">This is my second paragraph.</p>
<p id="p3">This is my third paragraph.</p>
<script>
document.getElementById("p2").innerHTML = "Updated!";
</script>
</body>
</html>


In this example, we used the "document.getElementById" function to reference the "p2" paragraph. Then the "innerHTML" for that paragraph was changed to "Updated!" by using the assignment operator. The assignment operator ("=") means to replace the current value with the new value. So the old sentence ("This is my second paragraph.") gets replaced with "Updated!".

We could make this even more interesting by also replacing the first paragraph with the current date and replacing the last paragraph with a random number:

<!DOCTYPE html>
<html>
<body>
<p id="p1">This is my first paragraph.</p>
<p id="p2">This is my second paragraph.</p>
<p id="p3">This is my third paragraph.</p>
<script>
document.getElementById("p1").innerHTML = "Date: " + Date();
document.getElementById("p2").innerHTML = "Updated!";
document.getElementById("p3").innerHTML = "Random: " + Math.random();
</script>
</body>
</html>


The "Date()" function and the "Math.random()" function are both standard Javascript functions. The "Date()" function produces the current date and time. The "Math.random()" function produces a random number between 0 and 1. These are being automatically converted to strings of characters when they are added to the "Date:" and "Random:" strings.

For this simple program, the date and random numbers are only refreshed when the page is reloaded. So click on your browser's "refresh" or "reload" button to watch the values change. But the point of these examples is that your Javascript program can use an ID value to select one of the elements on your page and change it. In this example, all three elements to be changed were paragraphs. And in all three cases, the text of each paragraph ("innerHTML") was changed by the Javascript.

Now we're in a better position to understand more of the example program presented in the second post above. Here's that code with the relevant sections highlighted:

<!DOCTYPE html>
<html>
<body>

<h2>My First JavaScript</h2>

<button type="button"
onclick="document.getElementById('demo').innerHTML = Date()">
Click me to display Date and Time.</button>

<p id="demo"></p>

</body>
</html>


We haven't covered creation of buttons yet, but the highlighted section is attached to the "onclick" behavior of the button. In other words, when the button is clicked, the following line will be executed:

document.getElementById('demo').innerHTML = Date()


In other words, the program will get the element with the ID of "demo" and set its innerHTML to the current Date (and time). So the button lets us refresh the date and time without having to reload the entire page.

All of the programs from this post are included in the attached .zip file.
 
 
Exercise 2 (Run each of the JavaScript Programs):

Copy each of the programs in this post and run them. You can copy each program and save it in a text file to open with your browser or paste each program into the w3schools web interface to run it.


 
Attachments
WriteWebPage.zip
(2.37 KiB) Downloaded 5 times
Join a National Hang Gliding Organization: US Hawks at ushawks.org
View my rating at: US Hang Gliding Rating System
Every human at every point in history has an opportunity to choose courage over cowardice. Look around and you will find that opportunity in your own time.
Bob Kuczewski
User avatar
Contributor
Contributor
 
Posts: 8339
Joined: Fri Aug 13, 2010 2:40 pm
Location: San Diego, CA

Re: Learn to Program: JavaScript

Postby Bob Kuczewski » Sat Sep 07, 2024 5:23 pm

Constants and Variables

One of the most important aspects of computer programming is managing data. Data is usually represented in the computer as either constants or variables. A constant is something like a number (such as 1 or 3 or -5 or 3.14159) or a string (such as "Hello" or "Hi there!" or "42"). A variable is a symbol that represents a value that might change. In a concrete sense, a variable provides storage space to hold a value. So while the constant 5 will always be a 5, a variable can have the value of 5 at one time and then have the value of 62.5 at another time. Most computer languages (including Javascript) use the "equal sign" ( "=" ) to assign values to variables.

Let's look at some simple examples. The following Javascript program creates 4 variables ("x", "y", "name", and "today"). Each variable is assigned a value (3, 25, "Steve", and today's date and time), but that value can change. Most of the values on the right of each equal sign are constants that are being assigned to variables.

<!DOCTYPE html>
<html>
<body>
<script>
x = 3;
y = 25;
name = "Steve";
today = Date();

</script>
</body>
</html>


If you run that program, you'll find no output. The variables are created and assigned, but they are not displayed. Let's add some statements to print those values to the document:

<!DOCTYPE html>
<html>
<body>
<script>
x = 3;
y = 25;
name = "Steve";
today = Date();
document.write ( "x = " + x + "<br/>" );
document.write ( "y = " + y + "<br/>" );
document.write ( "name is " + name + "<br/>" );
document.write ( "today is " + today + "<br/>" );

</script>
</body>
</html>


This program has 4 individual "document.write" instructions. Each one adds a string (like "x = ") to a number (like x) to another string (like "<br/>"). In Javascript (and many other languages), the adding of strings is the same as concatenation (the strings are simply joined together to make a longer string). Also, when strings are added to numbers, the numbers are first converted to strings so they can be concatenated. So this instruction (where "x" is 3):

document.write ( "x = " + x + "<br/>" );


produces an output that looks like:

x = 3<br/>


If you run the whole program, you should see the expected values printed in your browser window.

One of the best things about variables is that they can be changed and reused.

<!DOCTYPE html>
<html>
<body>
<script>
x = 3;
document.write ( "x = " + x + "<br/>" );
x = 7;
document.write ( "x = " + x + "<br/>" );
x = 12;
document.write ( "x = " + x + "<br/>" );
x = 5;
document.write ( "x = " + x + "<br/>" );

</script>
</body>
</html>


This simple example counts by adding one to the variable "x" again and again:

<!DOCTYPE html>
<html>
<body>
<script>
x = 0;
document.write ( "x = " + x + "<br/>" );
x = x + 1;
document.write ( "x = " + x + "<br/>" );
x = x + 1;
document.write ( "x = " + x + "<br/>" );
x = x + 1;
document.write ( "x = " + x + "<br/>" );
x = x + 1;
document.write ( "x = " + x + "<br/>" );
x = x + 1;
document.write ( "x = " + x + "<br/>" );
x = x + 1;
document.write ( "x = " + x + "<br/>" );
x = x + 1;
document.write ( "x = " + x + "<br/>" );

</script>
</body>
</html>


This isn't too bad for counting from 0 to 7, but it would be a lot of code to count to a thousand ... or a million! Here's the output:

x = 0
x = 1
x = 2
x = 3
x = 4
x = 5
x = 6
x = 7


The attached .zip file contains all of the programs from this post.

 
 
Exercise 3 (Run each of the JavaScript Programs):

Copy each of the programs in this post and run them. You can copy each program and save it in a text file to open with your browser or paste each program into the w3schools web interface to run it.


 
Attachments
Const_Var.zip
(1.03 KiB) Downloaded 3 times
Join a National Hang Gliding Organization: US Hawks at ushawks.org
View my rating at: US Hang Gliding Rating System
Every human at every point in history has an opportunity to choose courage over cowardice. Look around and you will find that opportunity in your own time.
Bob Kuczewski
User avatar
Contributor
Contributor
 
Posts: 8339
Joined: Fri Aug 13, 2010 2:40 pm
Location: San Diego, CA

Re: Learn to Program: JavaScript

Postby Bob Kuczewski » Sat Sep 07, 2024 8:21 pm

For Loop

The previous example showed a simple way to write a program to count. That example just added 1 to a variable (named x) again and again. Is there a better way?

It turns out that almost all computer languages have the ability to "loop". A programming "loop" executes the same instructions again and again. There are a number of different kinds of loops, but the most appropriate in this case is the "for loop" as demonstrated here:

<!DOCTYPE html>
<html>
<body>
<script>
for (x=0; x<=7; x=x+1) {
document.write ( "x = " + x + "<br/>" );
}

</script>
</body>
</html>


The "for loop" takes three expressions inside the parentheses. The first expression happens just once when the loop first starts. In this case, the first expression ("x=0") sets the variable "x" to 0. The second expression is the test. The loop continues as long as that second expression is true. In this case, the second expression is "x<=7". So the loop will continue as long as the variable "x" is less than or equal to 7. The third expression is executed each time the loop completes. In this case, the expression is "x=x+1". Since "x" starts out at 0, it will be changed to 1 at the end of the first time through the loop. It will be changed to 2 at the end of the second time through the loop, and so on. Eventually, the value of x will be changed from 7 to 8. At that time, x will no longer be less than or equal to 7, and the loop will complete.

The "for loop" will execute all of the statements between the opening and closing curly braces ("{" and "}"). In this case, we only have one statement between the curly braces:

document.write ( "x = " + x + "<br/>" ); 


So that one statement will be executed each time through the loop. Since "x" is changing each time through the loop, a different value will be written to the document each time.

Let's go though that more carefully.

When the computer reaches the "for loop" it will initially set the variable "x" to zero. Then it will ask whether "x" (now zero) is less than 7. Since 0 is less than 7, the computer will execute the "document.write" instruction. That instruction writes out the string "x = ". It also writes out the current value of the variable "x" (which is 0). It also writes out the string "<br/>" which is the HTML code for a line break (move to the next line). Then it adds 1 to x ("x=x+1"). So now the variable "x" will be 1. The computer will again ask if "x" (now 1) is less than or equal to 7. Since 1 is less than 7, the computer will again execute the "document.write" instruction and print out the new value of "x" as "x = 1" followed by a line break. It will again add 1 to x ("x=x+1"), so "x" will be 2. It will again check whether 2 is less than or equal to 7, and it will again write the message with the current value of "x" ("x = 2"). This process continues again and again writing "x = 3", "x = 4", "x = 5", and "x = 6". Eventually, x will become 7. At that point, it will again be written to the document ("x = 7"). Then it will again add 1 to x and x will be 8. It will again check whether 8 is less than or equal to 7. This time it will find that 8 is NOT less than or equal to 7, and the loop will be finally be finished. The program will have written the following to the document:

x = 0<br/>
x = 1<br/>
x = 2<br/>
x = 3<br/>
x = 4<br/>
x = 5<br/>
x = 6<br/>
x = 7<br/>


The "<br/>" portions will be shown as line breaks, and the final output will look like this:

x = 0
x = 1
x = 2
x = 3
x = 4
x = 5
x = 6
x = 7


Now that seems like a lot of work to count to 7. But by changing the for loop from "for (x = 0; x<=7; x=x+1)" to "for (x = 0; x<=7000; x=x+1)" the same program will count to 7,000. But even more importantly, the loop can do a lot more than just count. For example, just modifying the write statement will give us the values and the squares of the values:

<!DOCTYPE html>
<html>
<body>
<script>
for (x = 0; x<=7; x=x+1) {
document.write ( "x = " + x + ", x^2 = " + x*x + "<br/>" );
}

</script>
</body>
</html>


That "document.write" statement is a bit complicated so let's break it down. Here's the full statement:

document.write ( "x = " + x + ", x^2 = " + x*x + "<br/>" );


Here are each of the parts in that statement that are added together:

"x = "        <-- This is a string
x           <-- This is a number
", x^2 = "   <-- This is a string
x*x        <-- This is a number
"<br/>"       <-- This is a string


In Javascript (and many other languages), adding two strings just concatenates them. Also, when a number is added to a string, the number is converted to a string first and then concatenated as if it were originally a string. If we take "x=5" as an example, we start with the first string "x = " and add the value of x which becomes the string "5", so the concatenated string is:

x = 5


Then we concatenate the string ", x^2 = " to get:

x = 5, x^2 =


Then we concatenate "x*x". In Javascript (and many other languages), the asterisk ("*") is used for multiplication. So "x*x" is the same as 5x5 which is 25. When we concatenate that with the previous string we get:

x = 5, x^2 = 25


Finally, we concatenate the last string ("<br/>") for the HTML line break. That gives us:

x = 5, x^2 = 25<br/>


The final output (after computing all values from 0 to 7) will be:

x = 0,  x^2 = 0
x = 1, x^2 = 1
x = 2, x^2 = 4
x = 3, x^2 = 9
x = 4, x^2 = 16
x = 5, x^2 = 25
x = 6, x^2 = 36
x = 7, x^2 = 49


The "for loop" is extremely powerful, and it is one of the major workhorses in almost all procedural languages. It can count by 1. It can count by 2 or 3 or any value. It can loop through a sequence of items (like strings or images or pixels in images). It can be nested (one loop inside another) to process multi-dimensional tables or other complex data structures.


 
 
Exercise 4 (Run each of the JavaScript Programs):

Copy each of the programs in this post and run them. You can copy each program and save it in a text file to open with your browser or paste each program into the w3schools web interface to run it.


 
Exercise 5 (Modify one of the programs to print cubes up to 1000):

Copy one of the programs in this post and change it to print out cubes (x*x*x) rather than squares (x*x). Run it for values of x from 0 to 20. You can edit a text file to open with your browser or enter the program into the w3schools web interface to run it.


 
Attachments
For_Loop.zip
(554 Bytes) Downloaded 4 times
Join a National Hang Gliding Organization: US Hawks at ushawks.org
View my rating at: US Hang Gliding Rating System
Every human at every point in history has an opportunity to choose courage over cowardice. Look around and you will find that opportunity in your own time.
Bob Kuczewski
User avatar
Contributor
Contributor
 
Posts: 8339
Joined: Fri Aug 13, 2010 2:40 pm
Location: San Diego, CA

Next
Forum Statistics

Who is online

Users browsing this forum: No registered users and 4 guests

Options

Return to Technology Forum