Incorporating JavaScript into a Web Page - JavaScript Basics - JavaScript, 20 Lessons to Successful Web Development (2015)

JavaScript, 20 Lessons to Successful Web Development (2015)

PART I JavaScript Basics

LESSON 2 Incorporating JavaScript into a Web Page

image

To view the accompanying video for this lesson, please visit mhprofessional.com/nixonjavascript/.

The whole point of JavaScript is that it is designed to offer dynamic functionality to what previously were static web pages. Therefore, JavaScript code is generally embedded within the web page to which it applies. This can be in the form of embedding the code directly in the HTML document itself, or by means of a tag that tells the browser the location of a file containing some JavaScript to load in and execute. This external file may be on the same or a different web server.

Additionally, the location within a web page at which you insert the JavaScript (or link to a JavaScript file) becomes the default location in which any output from the JavaScript will be inserted. Of course, because it is a programming language, you can tell it exactly where in a web page to display anything, but if you use a simple JavaScript function such as write(), it will insert whatever is written in the current location.

Therefore, for this and other reasons, where you place your JavaScript can be important, and I will explain how you can choose the right location a little later on. First, though, let’s take a look at the basics.

Using Comments

Before looking at the JavaScript language and its syntax, I want to introduce the commenting feature. Using comments, you can add text to a JavaScript program that explains what it does. This will help you later when you are debugging, and is especially helpful when other people have to maintain code that you write.

There are two ways to create a comment in JavaScript, the first of which is to preface it with two slashes, as follows:

// This is a comment

You can place a comment after a JavaScript statement, like this:

anumber = 42 // Assigns 42 to anumber

Or, if you wish to temporarily restrict a line of code from executing, you can insert a comment tag before it and the statement will be completely ignored, like this:

// anumber = 42

Sometimes you need to be able to comment out more than a single line of text. In this case, you can use the multiline form of commenting in which you start the comment with /* and end it with */, like this:

image

image

As well as supporting extensive documentation, this form of commenting lets you temporarily comment out complete blocks of code by simply placing the start and end tags as required—something that can be extremely helpful when debugging.

Using Semicolons

If you like, you may add a semicolon after every JavaScript statement, and many programmers choose to do this. However, I prefer not to because semicolons are not mandatory. On the other hand, if you wish to place more than one statement on a single line, you must separate them with a semicolon. Therefore, for example, the three following sets of code are all valid syntax:

a = 1
b = 2

a = 1; b = 2

a = 1;
b = 2;

However, the following is not valid, as JavaScript will not know how to make sense of it due to the omission of a semicolon:

a = 1 b = 2

image

Think of the semicolon as acting like a newline as far as the JavaScript interpreter is concerned (or vice versa). If in doubt, always add one and, although you may end up with more semicolons than you need, at least your code will run correctly (assuming no other errors). In this book, however, I use semicolons only where they are necessary.

Where to Place the JavaScript Code

As previously mentioned, where you place your JavaScript code can make a difference. For example, if you wish default output to go straight into the current document, you may choose to place your JavaScript directly within the <body> and </body> tags. On the other hand, if you have a very long web page that takes more than a second or so to load, you might choose to place your JavaScript code within the <head> and </head> tags, so that it will be executed as soon as that part of the document is loaded in.

In the Document Head

To insert your JavaScript within the head of a document, you must place <script> and </script> tags where the script is to go, like this (highlighted in bold text):

image

In the Document Body

To insert your JavaScript within the body of a document, you must place <script> and </script> tags where the script is to go, like this (highlighted in bold text):

image

image

Including JavaScript Files

If you wish to keep your JavaScript code separate from your document contents (something you are likely to want to do once your JavaScript starts to become any length other than small), you can place it in its own file (usually with the file extension .js) and, instead of inserting script between <script> and </script> tags, you would include the code like this (highlighted in bold text):

image

If the script file is not in the current directory, you must include the path along with the filename, like this:

<script src=′pathtofolder/myscript.js’></script>

Or if the code is on another server, include the correct http:// (or https:// prefix, domain, and path) like this:

<script src=′http://server.com/folder/script.js’></script>

When including a script rather than embedding it in a web document, you may still choose where you wish to insert it, for example, into the body rather than the head, like this:

image

image

When you include an external JavaScript file this way, you must not have any <script> or </script> tags in the included document because a <script> tag has already been used to pull the file in.

JavaScript Language Syntax

I’ve already discussed some of the syntax used by the JavaScript language, such as how to comment out sections of code and where semicolons need to be used. But what is meant by syntax? Well, it’s a set of rules that define how to correctly structure a JavaScript program.

In this section I’ll outline the major syntax issues so that when you start programming, you’ll introduce the minimum of errors, so please forgive me if there’s a little overlap with earlier sections.

Case Sensitivity

JavaScript is what is known as a case-sensitive language. This means that it distinguishes between the use of the uppercase (A-Z) and lowercase letters (a-z). Therefore, for example, the variable MyVariable is quite different from myvariable (variables being special names used to stand in for values such as numbers or strings of characters, explained a little further on).

JavaScript will treat these as two totally different variables, so you need to be careful when choosing your variable names. Generally, I observe the following guidelines so that I can more easily go back and understand code I may have written in the past:

• All global variables that are accessible anywhere in a program are set to all uppercase, such as HIGHSCORE.

• Temporary variables used in loops are single letters in lowercase, such as j.

• Function names use a capital letter at the start of each word, like this: MyFunctionName().

This is only a naming convention that I use, and you may choose to apply different uppercase and lowercase rules to this, or simply stick to all lowercase—it’s entirely up to you.

Whitespace

Any spaces and tabs are known as whitespace, and any combination of these is usually treated by JavaScript as if it were a single space. The exception is when they are placed inside quotation marks, in which case they form part of a string, and all the characters are used.

Newline or carriage return characters are also treated as whitespace by JavaScript (unless within quotes), except that each one creates an implied semicolon, which, as you saw in the previous section, is used to denote the end of a statement. Therefore, for example, the statement a = b + c is valid on a single line, but if you format it as follows, a will be assigned the value in b and then an implied semicolon will be added, so that the + c line following is then interpreted on its own, causing a syntax error:

a = b
+ c

Variables

A variable in any programming language is simply a container for a value. For example, imagine that you have a few empty plastic pots into which you can place items (see Figure 2-1). Think of these as a metaphor for variables, in that you can take a small piece of paper and write the number 42, for example, on it and insert it into one of the pots. If you then take a marker pen and write MyVariable on the pot, it is just like a JavaScript variable being set using this line of code:

MyVariable = 42

image

FIGURE 2-1 An empty pot and blank piece of paper

Figure 2-2 shows the pot now labeled and the paper written on. You can now manipulate this variable in a variety of ways. For example, you can add another value to it, like this:

MyVariable = MyVariable + 13

image

FIGURE 2-2 The pot has been labeled and the paper written on.

This has the effect of adding 13 to the value of 42 already stored in the variable so that the result is 55, the new value held in the variable. This is analogous to taking the piece of paper with the number 42 written on it out of the pot labeled MyVariable, noting the value, adding 13 to it, and then replacing that piece of paper with another one on which you have written the number 55 (see Figure 2-3), which you then place back into the pot.

image

FIGURE 2-3 A new slip of paper with the number 55 on it

Likewise, you might issue the following command, for example, that will multiply the current value in the variable (55) by the value 3: MyVariable = MyVariable * 3. Again, this is equivalent to taking the paper from the pot, performing the multiplication, and placing a new piece of paper with the result of 165 (see Figure 2-4) back into the pot.

image

FIGURE 2-4 Another piece of paper with the number 165 on it

All the time the current numeric value is updated and popped inside the pot with the label MyVariable on it, so that any time that value needs to be referenced (looked up), the pot can simply be opened and the slip of paper inside then read.

Variable Naming

There are a number of rules governing how you use the JavaScript programming language. For instance, variables must begin with either an uppercase or lowercase letter (A-Z or a-z), or the $ or _ symbols. No other character may begin a variable name (except for some Unicode characters, but these should generally never be used in variable names).

Variables may not contain any mathematical operators (such as + or *), punctuation (such as ! or &), or spaces, but after the first character, they may include the digits 0-9 or any of the characters that can begin a variable name. All JavaScript keywords (such as window, open, string, and so on) are reserved and may not be used as variable names (although they can be used as part of a variable name, such as mywindow or string3).

String Variables

When a variable is used to store a number (as in the preceding examples), it’s known as a numeric variable. However, it’s also possible to store text in a variable, in which case the variable is called a string variable (because sequences of characters are called strings in programming languages).

Examples of strings include the name ″Bill Smith″, the sequence of characters ″A23bQ%j″, and even the characters ″123″ that, in this case, are a string of digits, not the number 123 (because of the quotes).

In the same way that you can store a number in a variable, so you can a string, and you use the same method of assignment, like this:

Name = ″Mary Jones″

Notice the use of double quotation marks around this string. These are what tell JavaScript that the value is a string and is how you can assign the string ″123″ to a variable, as opposed to the number 123, for example. In terms of the pot and paper metaphor, the preceding statement is equivalent to labeling a new pot as ″Name″ and writing ″Mary Jones″ on a piece of paper that you place in it, as shown in Figure 2-5.

image

FIGURE 2-5 This pot is labeled ”Name” and contains a string value.

Obviously, you can’t perform arithmetic on strings, but there are other actions you can take, such as shortening them; adding more characters to the front, middle, or end; extracting a portion of a string value; and more. For example, you can concatenate two strings together (attach one to the other) using the same + operator you use for performing additions, like this:

image

The result of these two statements is to concatenate the string ″Pharrell″ (first assigned to and then read from the variable Singer) with the string ″ Williams″ and place the resulting string back into the variable Singer. Lesson 4 shows some other operations you can perform on strings.

Using Quotation Marks in Strings

You have seen the use of the double quote character to indicate the start and end of a string, but you may also use the single quote if you prefer, like this:

Dinner = 'Fish and Chips'

The end result is identical, whichever type of quotation marks you use.

But there is a good reason why you may choose one type instead of the other, and that’s when you need to include a particular quotation mark within a string. For example, suppose you needed to store the string ″Isn’t the weather fine?″. As it stands, using double quotation marks works just fine, but what would happen if you surrounded the string with single quotation marks instead, like this: ′Isn’t the weather fine?′?

Well, you would get a syntax error because JavaScript would see only the string ′Isn′ and then some gibberish following it, like this: t the weather fine?′.

Then again what about the string ′Jane said, ″Hello″′? This time, this string works using single quotes, but because of the double quotes within it, if you were to surround the string with double quotes like this, ″Jane said, ″Hello″″, JavaScript would see one string, like this: ″Jane said, ″, some gibberish (to JavaScript) like this: Hello, and another string with nothing in it, like this: ″″. It would give up at all this and generate an error.

image

Placing a pair of quotes together with nothing between them results in what is called the empty string. It is commonly used for erasing or initializing the value of a string variable.

Escaping Characters

But things can get more interesting, because what about the occasions when you might require both types of quotes to be included within a string, like this: ″Mark said, ″I can’t wait″″? As it stands, this string will cause a syntax error, but you can easily fix it using the escape character, which is simply a backslash, like this: ″Mark said, \″I can’t wait\″″.

What the escape character does is tell JavaScript to ignore the \ character and to use the character following it as a string element, and not a string container.

You may escape either of the quotation marks inside a string to ensure they are used only as string elements, and can also use escape characters to insert other characters that you cannot easily type in such as tabs and newlines, as follows:

• \′ – single quote

• \″ – double quote

• \\ – backslash

• \b – backspace

• \f – form feed

• \n – newline

• \r – carriage return

• \t – tab

Variable Typing and Casting

In JavaScript, unlike some other programming languages, a variable can change its type automatically. For example, a string can become a number, and vice versa, according to the way in which the variable is referenced. For example, take the following assignment in which the variableMyVar is given the string value of ″12345″:

MyVar = ″12345″

Although the string is created from a group of all digits, it is a string. However, JavaScript is smart enough to understand that sometimes a string can be a number, so in the following assignment it converts the string value in MyVar to a number prior to applying the subtraction, and then the resulting value (which is now the number 12000) is stored back in MyVar, which is now a numeric variable:

MyVar = MyVar – 345

Likewise, a number can be automatically converted to a string, as in the following two lines, which first set the numeric variable Time to the value 6, then the string ″ O’clock″ is appended to the number value in Time, which is first turned into a string to make this string concatenation possible:

Time = 6
Time = Time + ″ O’clock″

The result is that Time is now a string variable with the value ″6 O’clock″.

Because of this changing of variables from one type to another (known as automatic type casting), it is not actually correct to think of JavaScript variables in terms of type, so I will no longer do so. Instead, you should consider only their contents and how JavaScript will interpret them.

However, sometimes it is necessary for you to force the type of a variable. For example, consider the following statement and ask yourself what you think JavaScript will do with it:

MyVar = ″12345″ + 678

If you think it will turn the string ″12345″ into a number and then add 678 to it (to result in the number 13023), you are unfortunately wrong. Although that might seem the appropriate action, JavaScript chooses to turn the number 678 into the string ″678″ and then concatenate it with″12345″, resulting in the string ″12345678″. If this is the result you want, then that’s good, but if not, then you must force the type that JavaScript should use by using the function Number(), like this:

MyVar = Number(″12345″) + 678

Now, before you say, “Why not simply make the string a number in the first place?” consider the case of already having the variable MyVar, whose contents may be either a string or number (and you do not know which), but you then must add a number to it (rather than append a string) like this:

MyVar = MyVar + 678

If MyVar happens to be a string, a concatenation will occur, but if it is a number, an addition will take place. In this case, it is necessary to use the Number() function to ensure you always get the correct result intended, like this:

MyVar = Number(MyVar) + 678

image

If you know for sure that you are only using numbers in a particular variable and it will never contain anything else, you will not need to use the Number() function to cast the value. Generally, the occasions on which you will find it beneficial to use casting are when dealing with values over which you have less control, such as user input that you are processing.

The Cast Functions

The following three functions are available for forcing the type of a variable (or casting it):

Boolean() Cast the value to either true or false.

Number() Cast the value to a number.

String() Cast the value to a string.

Values that are cast to Boolean can become one of only two values: true or false. Any string of at least one character in length, any object, or any number other than 0 will be cast to the value true. An empty string, the number 0, and the values undefined or null result in the value false.

When a value is cast to a number, if it is a string containing characters other than digits (or for another reason it cannot be converted to a number), then the JavaScript value NaN (for Not a Number) will be returned by Number(), instead of a number. Because NaN values cannot have arithmetic operations performed on them, any attempt to do so will see the value remain as NaN, so the following results in MyVar containing the value NaN, and not the value 23, as you might expect:

MyVar = Number(″A string″) + 23

The String() function is the most flexible in that it can safely turn any value into a string, even including JavaScript values such as NaN, null, undefined, true, and false.

Summary

We’ve actually covered quite a lot of ground in this lesson, which has explained some of the simpler JavaScript syntax and data handling capabilities. In the following lesson, we’ll start to see how these come together with operators to enable you to start creating simple JavaScript expressions.

Self-Test Questions

Test how much you have learned in this lesson with these questions. If you don’t know an answer, go back and reread the relevant section until your knowledge is complete. You can find the answers in Appendix A.

1. How do you create a single-line comment and a multiline comment?

2. Do you need to end lines of code with semicolons?

3. Name three places you can put JavaScript code in a web document.

4. Is JavaScript case-sensitive or case-insensitive?

5. Which characters can you use in a variable name?

6. With which operator do you add two values together?

7. With which operator do you concatenate two objects into a string?

8. How can you incorporate the same quotation mark within a string that encloses it?

9. How can you change a string to a number?

10. What does NaN stand for?