© The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2023
J. BartlettProgramming for Absolute Beginnershttps://doi.org/10.1007/978-1-4842-8751-4_8

8. Your First JavaScript Program

Jonathan Bartlett1  
(1)
Tulsa, OK, USA
 

So far, we have covered the basics of web page content (using HTML) and presentation (using CSS). As we noted, HTML is a markup language, which is used to tell the computer about the structure of text. CSS is HTML’s counterpart, acting as a styling language to tell the computer how you want the HTML to look. These are both limited, special-purpose document languages. They tell the computer about the static structure of a document, or set of documents, but not how to perform any function or computation. Neither HTML nor CSS is truly a general-purpose programming language. Therefore, in order to add interaction and computation to our web pages, we will need to use the JavaScript programming language.

This chapter covers one, short, simple program. However, it is important to read it in detail because we cover a lot of the terminology that we will use when talking about how programs and programming languages work.

8.1 A Short History of JavaScript

JavaScript was created by Brendan Eich in 1995, while he was working for Netscape (Netscape is now known as Mozilla). JavaScript was a revolution in the way that the Web worked because it moved the Web from being primarily a group of interlinked documents to being a truly immersive and interactive environment. Many developers (including myself) were initially skeptical of the usefulness of JavaScript when it first came out. Over the years, however, it has proved its usefulness. When it was first released, several other vendors tried to compete with JavaScript by having their own scripting language. The biggest of these was VBScript, implemented by Microsoft starting in version 3 of Internet Explorer (1996). However, by 2019, VBScript support has been officially removed from all browsers.

There have been other technologies that also make web pages more dynamic, such as Java, Flash, Silverlight, ActiveX, and other plug-ins, but these have not been nearly as integrated into HTML documents as JavaScript. These other technologies usually work by taking a specific area of your web page away from the browser and handling it itself. JavaScript, on the other hand, works as an integrated part of the web page itself. These other technologies were developed to augment areas where JavaScript fell short, such as animation, video, and integration with other parts of your computer (such as your camera) which are not normally part of the browsing process. JavaScript, however, has been slowly taking over these tasks as well, and today there is hardly any aspect of your browsing experience that isn’t available through JavaScript. JavaScript has withstood the test of time and continues to prove its usefulness.

One confusing thing about JavaScript is the name. As mentioned in the previous paragraph, there is another, different web programming language called Java. These are not the same thing, nor are they even very similar. It is important to always refer to JavaScript by its full name, because it works and acts significantly different from Java.1

Over the years, support and standardization of JavaScript has increased dramatically. In the early days of JavaScript, each browser handled JavaScript very differently, and it was difficult to write JavaScript that worked everywhere. Now, 30 years later, the situation is much improved. JavaScript was standardized by the ECMA under the name ECMAScript. Though it is standardized under a different name, this is the same language as JavaScript.

JavaScript is now by far the most standard way of developing interactive web pages. It is installed on every major browser, and almost all of the inconsistencies between the versions have been worked out. It is also supported by numerous third-party developers who write programming libraries (add-in functional modules) that provide JavaScript programmers with the ability to do just about anything imaginable.

A 14 line simple javascript program with a header tag, body tag, script type as text javascript, and declaring a variable to person age string, number, and age in twenty years without values. Finally gives an alert message as in 20 years you will be + age in twenty years + years old.

Figure 8-1

A Simple Web Page with a JavaScript Program

8.2 A Simple JavaScript Program

Instead of describing what JavaScript looks like and how it works, we will begin our study of JavaScript by just entering in an example program and afterward describing how it works.

Type the program shown in Figure 8-1 into your text editor, and save it as an HTML file.

After entering this program, load it in your browser. It will open up a dialog box asking you what your age is. It will then open up another dialog box telling you what your age will be in 20 years. Pretty simple, right? If your browser did not do these things, double-check to make sure you entered the code in exactly the same way it is listed. If it still doesn’t work, see Appendix B.6.

So let’s look at what this code does.

The first thing to notice is the <script> tag. This tag tells the browser that what occurs between the <script> start and end tags is JavaScript code. The browser will start running this code as soon as it comes across the end tag, even before it finishes loading the page. There are two possible attributes to the <script> tag. The one used here is the type attribute, which tells the browser what language the script will be in. This should always be text/javascript. The <script> tag can take another attribute, src, which tells the browser to look in another file (designated by the value of src) for the JavaScript code instead of it being in the web page itself.

After the <script> tag, there is a JavaScript single-line comment.
// This is a program in JavaScript

Whenever JavaScript code has two slashes together, from that point to the end of the line is considered a comment and ignored by the browser (see Section 6.6.6 for more information about comments). Another type of comment you will see in JavaScript starts with /* and ends with */ and is intended for comments which span multiple lines.

The first set of programming statements start with the word var:
var person_age_string;
var person_age_number;
var age_in_twenty_years;

var tells JavaScript that we need a temporary storage space, called a variable, to hold some data and gives that temporary storage space a name. Therefore, var person_age_string says that person_age_string is going to be the name of a temporary storage space which we will use to hold data. The way programmers state this is that var person_age_string creates a variable called person_age_string. This is also referred to as defining or declaring a variable. When we refer to person_age_string later, it will refer to this variable.

After this is a semicolon (;). In JavaScript, semicolons are used to separate statements from each other. So when we see a semicolon, we know we have come to the end of a statement.

The next two statements are just like the first, defining the variables person_age_number and age_in_twenty_years. Notice that we are using underscores (_) within the names of our variables. This allows us as programmers to see the words spelled out, but it makes sure that the computer knows that they are all one word. For instance, if I said “I am going to the bus stop,” you know that “bus stop” is really one word. However, computers are not that smart. Therefore, if you were talking to a computer, you would need to say, “I am going to the bus_stop” (notice the underscore), so that the computer knows that bus_stop should be treated as one word.

The next statement has a lot more action in it. Here is the code:
person_age_string = prompt("What is your age?");

There are several important things going on in this line of code. First of all, notice the equal sign (=). In most programming languages (including JavaScript), the equal sign is a command that says to put whatever value is on the right side of the equal sign into the variable on the left hand side. It does not say that these two things are equal already; it says to assign the right-hand value to the left-hand variable. This is known as an assignment statement. The left-hand side of this statement is one of the variables we just defined. This statement says that we should put a new value into that variable. The right-hand side of this statement tells what the value should be.

The right-hand side is where things get interesting. prompt("What is your age?") tells the computer to put up a dialog box, ask the given question, and then give back the value the user entered. This is called a function because it accesses functionality that is defined somewhere else. Functions in JavaScript start with the name of the function (prompt in this case), then an opening parenthesis ((), then the function parameters, and then a closing parenthesis ()). A parameter (also referred to as an argument) is a value that is sent to a function that the function uses to carry out its functionality. In this case, the function has one parameter, "What is your age?". This is a character string—a sequence of characters that are all combined together into a single unit (like we discussed in Section 4.4). In JavaScript, a string is enclosed in either double quotes ("), single quotes (), or backticks (`) and is treated as a single value, although you can also access the characters individually if you need to.2

We say that the parameter is passed to the function because the function will receive whatever value we put here. The prompt function can take either one or two parameters. The first parameter is the text you want to display to the user in front of the input box. The second parameter (which we are not using here) gives a default value to the user. If a function takes more than one parameter, each parameter is separated by a comma (,). So, if we wanted to give the user a default age, we would write it like this:
prompt("What is your age?", "25")

Remember that prompt is working with character strings, not numbers, which is why we put our default value in quotes. The code does not continue until the function is finished, which, in this case, means that the user has typed in a value and clicked “OK.” When the user does type something, that value is then used as the resulting value of the function. We say that the function returns that value.

Therefore, to use the terminology we have discussed so far, we say that the code prompt("What is your age?") calls the function prompt with a parameter "What is your age?" and returns whatever the user types as the value of that function.

Then, since the prompt function returns whatever the user types, the value that the user types gets stored into the variable person_age_string. Now, why did we call the variable person_age_string? Since we have no control over what the user types, we are getting what he types back as a string. We want the user to type in a number, but in reality he can type anything he wants—there is nothing to prevent him typing nonnumeric characters. Therefore, the prompt function always returns a string. Hopefully, the user did what we asked and typed in a number. But no matter what, prompt returned a string. We named the variable person_age_string so we remember that it is holding a string, not a number.

Now the program needs to add 20 years to whatever age the user typed. That isn’t currently possible, because we are holding the string that the user typed in, but we need a number in order to perform addition. The next line, person_age_number = parseInt(person_age_string), does the conversion we need. parseInt is a built-in function that takes a string and parses it into a number. Parsing is the process of taking a string and converting it into a more computerized representation that is easier for computer programs to manipulate. In this case, we are taking a string and converting (parsing) it into a number. parseInt is short for “parse integer,” where an integer is a whole number (i.e., 1, 2, 3, 4, etc.). If you wanted a number with decimals in it, you would use parseFloat, which is short for “parse a floating-point number,” with a floating-point number being a number with a decimal point in it (i.e., 31.25, 0.002, 23.12, etc.).

We then take the value from the parseInt function and store it into the person_age_number variable. Now we have the value we need in a variable as a number. Since it is a number, we can perform computations with it!

age_in_twenty_years = person_age_number + 20 tells the computer to add 20 to the value in the variable person_age_number and then store the result in age_in_twenty_years. In JavaScript, + and = are considered operators, and the values that they operate on are called operands. Operators are special built-in operations in the language. They differ from functions because, as we will learn, you can write your own functions, but the operators of a language are essentially fixed. Operators are used to do special tasks (such as assignment) or in places where making a function call would look funny. For math operations, for instance, it is more natural to write 2 + 3 than it is to write something like add(2, 3).

Now we now have the value we are looking for; all we need is to display it. The next line of code displays the value.
alert("In 20 years you will be " + age_in_twenty_years + " years old");

This piece of code has several strange features. First of all, it uses the plus sign (+) with strings. How would you add strings? Well, in JavaScript, when the plus sign is used with strings, it no longer means addition, but rather concatenation. Concatenation means joining two things together. In this case, we are joining strings end-to-end. There is one problem—age_in_twenty_years is not a string but a number! JavaScript handles this automatically by converting anything that is added to a string into a string before the addition takes place. So, the plus sign indicates addition if it has numbers on both sides but concatenation if there is a string on either side of it. In addition, concatenation will convert the other value into a string if it isn’t one already.

Another interesting feature of this code is that it combines several operations. It concatenates three items together and then passes the resulting string to the alert function. In most programming languages (including JavaScript), you can combine as many operations and functions as you want together to give you the final value. The innermost operations are performed first, and their results are then passed as inputs to the more outer operations.

Finally, this code introduces the alert function, which displays a popup to the user. The alert function returns when the user clicks on the “OK” button.

A hand icon with its index finger pointing towards the right. Practice Questions
  1. 1.

    What is a variable and how do you declare it in JavaScript?

     
  2. 2.

    What are the two different uses of the plus sign in JavaScript?

     
  3. 3.

    What do the prompt and alert functions do?

     
A hand icon with its index finger pointing towards the right. Practice Activity
In this activity we will try to modify the program in this section. Be sure that you have the original program working correctly before you begin the activity. Test your program after each step to make sure it is still working. If you wait until the end, and it doesn’t work, you won’t know where you made the mistake.
  1. 1.

    Add an alert before your prompt that simply says “hello.”

     
  2. 2.

    Change the number of years added to 25. Be sure to change the final alert as well so it says the right thing!

     
  3. 3.

    Can you figure out how to combine the lines with the prompt and parseInt into one another so that the output of prompt becomes the input of parseInt? What variable is no longer needed in this case?

     

8.3 Moving the JavaScript to Its Own File

Just like CSS, JavaScript can either be embedded within your HTML file or stored in a separate file. My recommendation is to always keep your JavaScript in a separate file unless you have a specific reason to include it in your page. Sometimes the interaction between JavaScript and HTML can lead to unexpected results, such as the browser confusing some parts of your JavaScript with HTML tags. By keeping your JavaScript code in a separate file, these issues are avoided.

A 7 line H T M L code with header, body, and footer section. The body section has a heading as a simple javascript program and a script tag with script type as text javascript, source as application dot j s.

Figure 8-2

HTML File Referencing External JavaScript

In order to put your JavaScript into a separate file, all you need to do is copy the code between the <script> start and end tags and paste them in a new text document with the extension .js. Then, modify your <script> tag to have a src attribute (keep the type attribute the way it is) with the relative URL of your new JavaScript file. If we named our JavaScript file application.js and put it in the same folder as our HTML file, the HTML would look like Figure 8-2, and the JavaScript would look like Figure 8-3.

Keeping your JavaScript in a separate file has other advantages as well. First of all, it makes your HTML pages easier to read because they only have one language in them—HTML. By keeping your languages separated in their own files, you keep more of your sanity intact. Another reason is that it allows you to share JavaScript programs and pieces of JavaScript programs between multiple web pages so you don’t have to write or copy the same code over and over again. This also means that if you change your code in one place, you don’t have to search for and make the same change on every other page, a process which is both tedious and error-prone. If you have a large JavaScript application, separating your JavaScript can actually make your pages load faster because your browser only has to load your JavaScript once rather than have it take up space implanted in the middle of each file.

A 7 line simple javascript program declares a variable to person age string, number, and age in twenty years without values. Finally gives an alert message as in 20 years you will be + age in twenty years + years old.

Figure 8-3

Short JavaScript File Referenced from HTML

8.3.1 Review

In this chapter, we covered the absolute basics of how to write a JavaScript program. We have learned the following:
  • JavaScript is a general-purpose programming language that allows us to create dynamic web pages.

  • ECMAScript is the name for the language used by the group which standardized it, but it is usually still referred to by most people as JavaScript.

  • JavaScript can either be included on a page or stored in a separate file.

  • JavaScript is designated in web pages using the <script> tag.

  • Variables are storage locations for values and are declared using the var keyword.

  • The = operator is used for assigning a value to a variable.

  • Functions are named processes that are defined elsewhere.

  • Functions can be given values, called parameters (or arguments), which are used by the function when it runs.

  • Multiple function parameters are separated by commas.

  • When functions complete, the value they give back is called the return value.

  • JavaScript uses quotes (, ", or ) to signify character strings.

  • prompt is a function that brings up a dialog box for the user type in a character string and returns that character string.

  • parseInt is a function that converts a string to a number.

  • alert is a function that brings up a dialog box with a message.

  • The + operator either adds (in the case of numbers) or concatenates (in the case of strings).

8.3.2 Apply What You Have Learned

  1. 1.

    Create a new JavaScript program that asks the user for two values. Convert these values to integers, and then add these values together and display the result.

     
  2. 2.

    Try to rewrite the program you just created so that it doesn’t use variables. Hint: Make the return value of your functions be the parameter to other functions. It also might help to combine code a piece at a time, eliminating a single variable each time.

     
  3. 3.

    What happens on these functions if you type in something that isn’t a number? What does it display? Why do you think it does that?

     
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
44.211.24.175