Let’s Learn JavaScript • Lesson 4 • Planning a Script

📅 July 24, 2017
A script usually refers to a short program executed by an interpreter. Python, Perl, and JavaScript are examples of interpreted scripting languages. When we code client-side JavaScript, we write scripts that run in web browsers.

Scripts are intended to be lightweight and short in order to consume fewer system resources than full-fledged applications. This way, pages render faster in a web browser.

The purpose of using JavaScript in a web page is to make the page interactive either with the user directly or with a web server. Interactive pages are dynamic — page contents can change as the page is loaded or while the page is being viewed. JavaScript can access and modify page content and react to user input, such as button clicks or form entry. The result is a web page that feels more alive compared to static content that does not change.

No matter how simple or fancy a script might be, we need to plan before writing any code.

Overview

  • Planning a Script
    • Specify the goal
    • Design the goal as steps
    • Write the code for each step
  • Plan Before Coding!
  • Planning the Steps
  • Flowcharts
    • Basic Flowchart Symbols
  • Writing the Script
  • How It Works
    • Sentinel-Controlled Loop
    • Comments
    • Algorithm in Comments
    • Fancy Comment Title
    • Be Careful! Comments Are Public
    • Prompt for Score
    • Is the Input -1?
    • Record input in array
    • Exit the loop
    • Find the highest score and display it
    • Injecting HTML

 

Planning a Script

Computers are dumb. They might seem intelligent, but this is only after they have been told what to do. A computer can only think in 0’x and 1’s, but it can think very, very fast. So fast, in fact, that the thinking can be measured in billions or trillions of operations per second depending upon the speed of the hardware.

A program or script tells a computer what to do. When we write a script, we write in a language using grammar close to what we understand. This is then converted into instructions that are executed on the processor.

We cannot directly tell a process to “show the highest score.” We must break down the process into a series of steps, and then write code to tell how each step must be performed and in what order.

Planning a script consists of three steps itself:

Step 1: Specify the goal.

Boiled down to one statement, what is the core of your program? What is the main purpose? IN the example above, the goal is to show the highest score.

Step 2: Design the goal as steps.

Exactly how will we show the highest score? Do we already have a list of scores to choose from? Will we ask the user to enter them? Once we have the scores, how will we determine which is the highest? Will we need to sort them in any way? If so, what sorting algorithm will we use?

These are important questions to ask because they will determine what kind of code you will need to write.

Step 3: Write the code for each step.

This is when the actual programming occurs. Step by step, convert the ideas into a series of statements that the computer can execute.

Plan Before Coding!

When people think of programming, they tend to think of a mentally-gifted, obese, nerdy, pimply-faced geek hunched over a keyboard in a dimly-lit room or a gloomy, tie-toting corporate slave stuck in a sterile office cubicle hammering away to meet a deadline. Both sit down, write code from memory, and fifteen minutes later a flawless masterpiece runs perfectly upon the first try.

This is not true.

All good coders have notebooks, sketches, flowcharts, and reference material easily accessible, and they consult them while programming. The best programmers always plan and design their programs before they write a single line of code. As a result, the coding stage usually takes less time.

RULE: Always plan your script before writing the code.

No matter how big or how small your script might be, always, always, always think through “How will this work?” and write steps or draw diagrams to that show how the script will operate. This is not a sign of weakness or stupidity. It is a sign of intelligence and careful planning.

“But I don’t need to plan. I already know how the program should run in my head. Planning is for beginners. I am l33t!”

Nobody is that good. Sure, simple toy scripts and examples whose only purpose is to illustrate programming concepts might not require planning, but if you intend to write any serious code — whether a simple JavaScript slideshow or an interactive quiz game — then you need to plan your script in advance or else you will spend more time to finishing it than expected.

Too many times I have witnessed arrogant coders plunge into writing code without doing the necessary planning. They would fire up an IDE or text editor and start programming. In the beginning, their fingers would fly over the keyboards like virtuoso pianists as they coded the basics, eventually they would hit a wall and stare at the monitor perplexed.

They would halt. They stare and stare and stare. Pluck. Pluck. Pluck. A few more half-hearted keystrokes would be heard, and then more staring as productivity ground to a halt.

The more code they added to resolve the situation, the more bloated and convoluted the program would become. As more code was added, they would become more reluctant to delete anything — because somewhere in that mess exists the key that makes the program semi-functional — and we cannot delete that, can we?

The answer? Add more bandage code to plaster over the messy code. The resulting program would run with errors and feel “shaky” to the user. This also made it a nightmare to debug and maintain over time. Without plans, how will any programmer understand it without wading though lines upon lines of spaghetti code? This wastes time.

If you develop the habit of planning your script before writing code, you will find that your plans give you focus, and you will finish writing your script faster.

Planning need not be a formal process. You are not going to frame your flowcharts. You want a map. A guide. At the very least, scribble your ideas on scratch paper or on a napkin. Use a snotty tissue if you must. Having something is better than having nothing. A notebook is best. If you hate paper, records your brilliant ideas in a text file or the comments of your code. Use drafting programs, such as Dia, to create flowcharts. Draw. Think. Design. The good programmers do this (especially those on a programming team), and they create well-written code that is understandable and maintainable with fewer lines of code. Some code is a work of art worthy of framing the printout.

Beginners might dislike planning, but planning is so important that it is worth repeating:

RULE: Always plan your script before writing the code. NEVER plunge into coding without a plan written down. Do not rely upon the “plan in your head.”

“Won’t the plans change during programming?”

Yes, they will. Many times, the completed script will little resemble the original plans and flowcharts. During coding, you will often encounter scenarios that you did not think of before. Inspiration will often show you a better way to achieve a process than what you had originally planned. If so, return to your plan and revise it to show the new idea. Update the flowcharts if required. Try to keep you plans updated. You will thank yourself and kiss your reflection in the mirror should you even need to revisit your code months later

“If that is the case, then why bother planning at all?”

To make your goals clear and give you direction. You will get stuck during coding, but a plan acts as a roadmap to refresh your mind and help keep you focused. Having no plans at all leads to a staring contest between you and your monitor — and your monitor always wins until the screensaver activates.

“I will write down how my program works and comment my code *after* it is finished. This way, I do not need to keep updating my plans and comments. Commenting takes too much time.”

Then, you missed the point. You might get by with kiddy-simple code, but serious programs and scripts require planning before coding in order to stay on track and produce professional results. Programming teams are often required to plan ahead. If you are programming alone, then nobody will make you plan. Do as you please. But after a while, everyone gets tired of encountering mental roadblocks and seek a better process. Develop the habit of planning now so it becomes second nature as project increases in complexity.

Planning the Steps

With the goal clearly defined, list an overview of the general steps. Avoid details for the overview. Just show the steps.

We are going to write a script that prompts the user for a series of scores and then quit when -1 is entered. (All scores will be 0 or greater.) Once all scores have been entered, the highest is determined and displayed in the web page.

What is the highest score from a series entered?

The list of steps would look like this:

1. Prompt user for score.
2. If score greater than or equal to 0, record and prompt again.
3. If score is -1, then do not record and proceed to 4.
4. Get highest score.
5. Display the highest score.

These steps took less than thirty seconds to think through and write down, but already the focus is clear. It is only a matter of writing the code in JavaScript.

When we write steps like this, we are writing an algorithm. Algorithms are necessary because computers think programmatically. That is, they execute instructions in order, one at a time. Instructions might branch to other instructions and then return to other points, but only one instruction is processed at a time. This is why we must break a complex down into simple tasks using steps.

(In the case of multi-core processors or multiple, distributed processors, more than one instruction can execute simultaneously. For the purpose of this tutorial, let us assume that a processor executes one instruction at a time.)

Flowcharts

A flowchart is a visual diagram that shows how a program works. Using specialized symbols and arrows, we can see the flow of a program as it is intended to run.

Flowchart of the highscore script. Created from the algorithm. Flowchart made using the program Dia.

Programming flowchart symbols. Each symbol’s purpose is denoted by its shape.

Program flows from top to bottom beginning at the event symbol and ending at the End symbol. Execution follows the direction of the solid arrows.

Each block in the diagram is a flowchart symbol whose shape indicates the intended purpose. For example, a diamond symbol indicates a Yes/No or True/False decision. The path of program flow is illustrated with lines and arrows.

Each symbol usually has one input and one output. When program flows into an existing line, for the repeat as shown at the top, point the arrow into the line, not into another symbol. A decision symbol has one input but two outputs based upon the True/False result of the condition written.

Other flowchart symbols exist, but these are suitable for most scripts. The point is to help visualize what happens during a script’s execution flow. Use what works best for you. In this case, I used an extra symbol for internal storage to denote that the scores will be stored in an array. Arrays will be covered later, but think of an array as a storage bank of similar items. In this case, numbers that represent scores.

I used dotted lines to show data flow in order to keep it separate from program flow — the order of code execution. Try to develop flowcharts based upon standards, but feel free to take liberty in areas that help you understand the program or better illustrate the purpose.

This flowchart illustrates a top-level approach. It is possible to have multiple flowcharts. For example, the process symbol labeled “Find the highest score from array” does not show the details involved in locating the highest score. We could write a second flowchart that would elaborate this step if we wanted to. The point of a top-level flowchart is to show that this step exists and where it exists.

Writing the Script

Now, we can write the script! Below is the JavaScript version of the algorithm and flowchart previously developed. Do not be alarmed if the script makes little sense at this point. We will cover programming details later.

 

HTML (left) and JavaScript (right). Include the JavaScript as an external script. This keeps the behavior (JavaScript) separate from the content (HTML).

Type this script for yourself and execute it in a web page as an external script.

Firefox. The “Highest Score” header appears first and then the JavaScript executes because the script is reference after the h1 element in the markup. Firefox prompts the user to enter a score or -1 to quit.

Entering the value 2300. Press Enter on the keyboard or click the OK button to register the number.

Entering a second number: 45.

Preventing Additional Dialogs

Notice the Firefox option  to prevent additional dialogs? This is a browser feature that your script has no control over. When multiple dialogs are displayed successively as in this case, Firefox, as well as other browsers, will include an override feature that lets you choose to prohibit any more dialogs from appearing on the page.

This is a necessity, not an annoyance. Browser window dialogs (alert, prompt, confirm) have been abused so much in the past by rogue web sites, malware, and “trick” sites that browser now enforce this disable option. This way, a user cannot be trapped on a web site. Yes, some web sites refuse to let users go and insist on asking “Are you sure you want to leave this site?” over and over and over and over again until you feel like unplugging your computer from the electrical outlet. These dialogs are modal, which means that you cannot do anything else on the page until you respond.

Entering another core: 23000.

We are finished, so enter -1. The -1 will not be included as an entered score because this is the sentinel value.

The script finds the highest score, 23000, and displays it along with the text. refresh the page to try again.

How It Works

Sentinel-Controlled Loop

This is an example of a sentinel-controlled loop. This is a loop that continues to repeat until a preset value, called the sentinel value, is entered. The sentinel value is not included in the result. In this script, the sentinel value is any negative number.

Comments

Comments at the beginning of the script help describe what the script does and may provide additional notes.


Comments notate your code for better understanding. Comments are not processed during execution, so you are free to add notes as you like to aid understanding.

Always comment your code!

Avoid commenting the obvious, such as “This is a while loop.” We can recognize a while loop. Instead, add a brief, one-line comment that states the goal of the while loop block.

A single-line comment provides a brief description of the entire while loop.

There are two types of comments: Multi-line comments and single-line comments.

Multi-line comments begin with /* and end with */. All text within /* and */ is a part of the comment and ignored by the JavaScript interpreter. You may add whitespace and new lines as you like without extra /* */.

Single-line comments begin with // (two forward slashes) and end until the end of the line. These are useful for one-line phrases that describe a block or section of code, such as a loop.

Notice that the while loop uses a single-line comment to describe the purpose of the entire loop. There is not a comment for each line within the loop since that is over-commenting and unnecessary. Instead, I used appropriately-named variables and a well-named array to make the code self-explanatory.

Algorithm in Comments

We can use the comments to outline the algorithm.

Below the main description is the algorithm listing.

This helps organize the steps needed for the script and to explain it to future programmers who might need to maintain the code…or refresh your own memory should you review this script several months in the future.

We did not write the goal since that is already handled by the brief description. Single-line comments are useful for indicating the steps within the script.

Set up the script template with comments for better organization.

With the comments in place as a template, we can write the code in the appropriate places. Doing this helps stay focused and helps describe what the script will do.

Fancy Comment Title

Notice the “Highest Score” text in the comments?

ASCII art makes comments more interesting! It can highlight the title of the script.

This was created using figlet in Bash. figlet is program that creates styled ASCII-art text. It has no effect other than the fun-factor. Comments should be fun and interesting!

To use figlet for yourself, first install it (Linux-only).

 sudo apt-get install figlet

Then, execute figlet in a terminal:

 figlet -f small "Highest Score"

Everything within the double quotes will be converted into styled text that you can then copy and paste into the comment section of the JavaScript file.

Linux Mint 18.2 terminal. figlet using the small font. The -f option specifies which font to use.

Be Careful! Comments Are Public

Remember that web content is public information. Anyone can open the source of your web page, stylesheet, or JavaScript file and peruse its contents. This included comments, so avoid including any personal information, such as your name, credit card information, home address, list of friends, or anything that you are not comfortable sharing on the Internet.

 // Create a blank array
 var arrScore = new Array();

Like the single-line comment says, this line creates a new array. Since we do not know how many scores will be entered, we will declare a blank array. Arrays will be covered later.

 // Sentinel-controlled loop (Negative anything exits)
 while (true)
 {
     var input = prompt("Please enter a score (-1 to exit)");
     if (input >= 0)
         arrScore.push(input);
     else
         break;
 }

A loop is a programming construct that repeats until a certain condition is met. In this case, the loop repeats forever until a sentinel value is entered. The sentinel value here is -1. The user sees “Please enter a score (-1 to exit)” instruct the user to enter -1 to quit. Other negative values, such as -567, will be accepted into the array. This is fine for our purposes.

Prompt for Score

var input = prompt("Please enter a score (-1 to exit)");

This displays a modal dialog in the browser window that asks the user to enter a score or enter -1 to quit.

Is the input -1?

if (input != -1)

Here is the code version of the flowchart’s decision symbol. If the value the user entered is not equal to -1 (denoted by != -1), then we will assume that it is a score and store that value in the array by pushing it onto the array with the push() method.

Record input in array

arrScore.push(input);

This tells JavaScript to take the input and add it to the array. Existing values are not replaced. The array will grow as more items are added.

Since the sentinel value was not entered, the loop repeats by prompting again.

Exit the loop

If the user entered a negative score, then it is not saved in the array. Instead, the loop quits immediately with the break statement.

Find the highest score and display it

// Find the highest score in array and display it
document.write("<p>Highest score entered: " + Math.max.apply(Math, arrScore) + "</p>");

This statement performs two steps together. Working from the innermost parentheses, we use Math.max.apply() to find the highest score in the array, and then we pass it to document.write() to display it on the web page.

No more statements exist, so the script terminates and we see the result in the browser.

Injecting HTML

Notice the p tags in this line?

document.write("<p>Highest score entered: " + Math.max.apply(Math, arrScore) + "</p>");

All text within the double quotes is displayed in the browser document. <p> and </p> are present within the double quotes, but they are not shown. Why? Because the browser interprets them as HTML and processes them as markup.

In HTML, the effect would be the same as,

<p>Highest score entered: 23000</p>

This is how we can use JavaScript to inject elements into a page during rendering in order to produce dynamic content. We could modify the p elements to become h2 elements.

Changed p tags to h1 tags on line 42.

Firefox. Entering 4500 as the highest score.

High score appears as a level-two header instead of a normal paragraph.

Again, <h2></h2> is seen as markup by the browser, so the inner text is rendered as a level two header. We can do the same with any HTML to allow JavaScript to customize the markup on a page.

Hey! This Script Has Problems!

Entering -1 before entering any score shows 0 in the result.

What do we do with text?

We would not want to use the script in its current form on a final web page. We would need to add error-checking code to handle situations that might confuse the user of cause the script to display erroneous results.

Error-checking and input validation are subjects for another time. They were omitted here for brevity and for illustration.

As a side project, can you figure out how to modify the code so that an alert dialog displays a message if the user clicks the Cancel button? The script in its current form does nothing but repeat when Cancel is clicked.

Have fun!

 

Advertisements

,

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: