Make an active site

What you have learned

This has been another busy chapter. We’ve covered a lot of ground. Here is a recap, along with some points to ponder:

  • A web page can contain input elements that are used to read values from the user. An input tag can have different types, such as text, number, password, date, and time. The value of an input tag is always delivered as a string and needs to be checked for validity before it is used. The input tag behaves differently in different browsers.

  • The Number function converts a string of text into a number. If the text does not contain a valid number, the function will return NaN. If the text is empty, the function returns 0.

  • A browser provides local storage where a JavaScript application can store values that persist when the web page is not open. Local storage is provided on a per-site basis (meaning each top domain has its own local storage). Local storage is implemented as named strings of text. The Application tab of the browser’s Developer Tools can be used to view the local storage contents. Local storage is specific to one browser on one machine.

  • JavaScript variables can be declared local to a code block using the keyword let. These variables are discarded when program execution leaves the block where they are declared. Using let to declare a variable in an inner block “scopes out” a variable with the same name declared in an enclosing block. An attempt to use a variable outside its declared scope will generate an error and stop the program.

  • JavaScript variables can be declared global using the var keyword. Variables declared using var in a function body are global to that function but not visible outside it. Variables declared using var outside all functions are global and visible to all program functions.

  • Global variables represent risk. Any code can view a global variable in the program (which represents a security risk), and any code can change it in the program, which represents a risk of unintentional change or attack vulnerability.

  • Variables not explicitly declared (not declared using let or var) are global to the entire program. This dangerous default behavior can be disabled by adding a “use strict' statement to the function or at the start of the entire program.

  • You can declare a variable using const, which prevents the value assigned to the variable from being changed.

  • A JavaScript program can add elements to the DOM, making it possible for the contents of a web page to be created programmatically rather than being defined in the HTML file describing the page. You can view the elements in a web page (including those created by code) by using the Elements view in the Developer Tools.

  • An element created in a JavaScript program can have additional attributes added to it. We used this to allow a button in the Cheese Finder game to hold its x and y grid position.

  • Creating a new HTML element in a JavaScript program does not automatically add it to the page. The appendChild function can be used on the container element (such as a paragraph) to add the new element. When the element is added, the page will be redrawn, and the new element will appear on the display.

  • The JavaScript this keyword can be used in the string of JavaScript bound to an event handler. In this context, the this keyword provides a reference to the object generating the event. In the case of the Cheese Finder program, we use this to allow 100 buttons to be connected to the same event handler. By passing the value of this into the event handler, we can tell the handler which button has been pressed.

  • It is also possible to use the addEventListener method provided by an element instance (in our case, a button in the Cheese Finder game) to specify a function to be called when the event occurs. The event handler function is provided with a reference to the event details when it is called. These details include a reference to the object that caused the event.

  • JavaScript provides a Math.random function that produces a random number in the range of 0 to 1. We can multiply this value by a range to get a number in that range.

To reinforce your understanding of this chapter, you might want to consider the following “profound questions”:

Question: Does the user always have to press a button to trigger the reading of an input?

Answer: You can use the onInput event to specify a function to be called each time the content of an input box changes. This means if the user was entering a number, the onInput function would be called each time a digit was entered.

Question: Is Number the only way to convert a string to a number?

Answer: No. JavaScript provides called parseInt and parseFloat functions, which can be used to parse a string and return a value of the requested type. These behave slightly differently from Number. A string that starts with a number would be regarded as that number. For example, parsing 123hello would return the value 123, whereas Number would regard this as NaN. The parse functions also regard an empty string as NaN. It doesn’t matter whether you use Number or the parse functions; just be mindful of the slight differences in behavior.

Question: How much local storage can I have on a website?

Answer: The limit is about 5MB for a browser on a PC.

Question: How long are variables stored in local storage?

Answer: There is no limit to the time a value will be stored.

Question: Can I delete something from local storage?

Answer: Yes, you can. The removeItem method will do this. However, once deleted, it is impossible to get the data back.

Question: How do I store more complex items in local storage?

Answer: Local storage stores a string of data. You can convert JavaScript objects into strings of text encoded using the JavaScript Object Notation (JSON). This allows you to store complex items in a single local storage location. You can find out more about JSON in the section “Transfer data with JSON” in Chapter 5.

Question: How do I protect items stored in local storage?

Answer: You can’t protect values in local storage. They are public. The only thing you could do is try to encrypt the values so that they can be read but not understood. Never store important data in local storage. You should store such data on the server that users cannot access. We will do this in Chapter 10.

Question: Can I stop someone from looking through my web page’s JavaScript code?

Answer: No. There are tools you can use that will take your easy-to-understand code and make it much more difficult to read. These are called obfuscators. However, there are also some tools that can decode obfuscated code. The only way to make a properly secure application is to run all the code on the server, not on the client. We will do this in Part 2, “Make a Cloud-based application.”

Question: What is the difference between let and var?

Answer: A variable declared using let will cease to exist if a program leaves the block in which the variable was declared. This makes let very useful for variables you want to use for a short time and discard. A variable declared using var has a longer lifetime. If it is declared in a function body, the variable will exist until the function exits. A variable declared as var at the global level (outside all functions) is global and will be visible to code in all the application functions. Global variables should be used with caution. They provide convenience (all functions can easily access their content) at the expense of security (all functions can easily access their contents).

Question: What does strict do?

Answer: Strict mode changes the behavior of the JavaScript engine so that dangerous program constructions are rejected. One of the things that strict does is stop the automatic creation of global variables when a programmer doesn’t specify let or var at the variable creation.

Question: When do I use a constant?

Answer: You use a constant when you have a particular value that means something in your code. Using a constant makes it easy to change the value for the entire program. It also reduces the chance of you entering the value incorrectly. Finally, it lets you make a program clearer. Having a constant called maxAge in a program, rather than the value 70, makes it very clear what a statement is doing.

Question: Can document elements created by JavaScript have event handlers?

Answer: Yes, they can. We have actually done this. The best way is to use the addEventListener to specify the function to be called when the event occurs.

Question: How does an event handler know which element has triggered an event?

Answer: We have done this in two different ways. In the first version of Cheese Finder, we added a this reference to the function call that handled the event. This function was specified in the text of a function call bound to the onClick attribute added to each button element. The function then received the this reference (which, in this context, is set to a reference to the element generating the event) and used it to locate the pressed button.

The second (and more flexible) way we did this used the addEventListener method on the new button to add the event handler. When the browser calls the event handler in response to the event, it is passed a reference to an Event object containing information about the event, including the target property containing a reference to the element generating the event.