ALGEBRA  QUIZZES  AND  ILLUSTRATIVE  COMPUTER  CODE     

JavaScript-1

Click (below) and watch a JavaScript program solve this equation:

$$\begin{equation} 3x+6=24 \end{equation}$$

Here's the code

JavaScript code Comments
   
 1   var right_side = 24; // Creates a variable named 'right_side' and initializes it with the value of the right side of the equation (24).
 2   var left_side = 0; // Creates a variable named 'left_side' and initializes it with the value 0.
 2   var x=1; // Creates a variable named 'x' and initializes it with the value 1.
 3   for (x = 1; x<= 30; x++) { // The for keyword starts a loop that runs from x=1 to x=30. JavaScript keywords are printed in bold type.
 4       left_side = 3*x+6; // Computes the left side of the equation (3x+6) using the current value of x, and updates the value of 'left_side'.
 5       if(left_side == right_side) { // The if block uses == to check if both sides are equal yet. If yes, proceed to the next line. Otherwise, continue.
 6          console.log("Answer: "+x); // If left_side = right_side (the if statement was true), that means we found the answer and we'll print it out here.
 7          break; // Breaks out of the enclosing for loop. (Without this statement, the loop would continue running up to 30.)
 8       } // If statement closing brace.
 9  } // For loop closing brace.

Try it yourself. It's easy!

JavaScript is one of the most widely-used programming languages in the world! Why? Because JavaScript comes with every Web browser that accesses the World Wide Web. And who doesn't access the Web today? There are several ways1 to learn JavaScript on your own.

In this example, we are going to enter and run the above computer program (JavaScript code) in Philip Guo's excellent visualizer, Online Python Tutor. (Despite its name, Online Python Tutor also works with JavaScript, Java, and TypeScript.) Once you get the hang of it, you'll be able to create and visualize your own programs! So let's get started.

The algorithm we'll be using is called exhaustive search. Here's how it works: One-by-one, we'll plug a series of different values into x and check to see if that particular value makes both sides of the equation equal. If it does, then that value of x is a solution to the equation (it makes both sides equal), and we'll print the answer.

Notice that exhaustive search just checks all possible solutions within our specified range of 1-30 (line 3 above); it doesn't use any tricks to reduce the number of guesses needed. But since computers can make millions of guesses per second, exhaustive search is actually a pretty good algorithm for many applications. In future examples, we'll look at other algorithms that do use tricks to cut down on the number of guesses and the time it takes. Reducing processing time is especially important in programs that crunch big data sets, such as weather forecasting, problems in science and engineering, and heck, even some areas of biology. (Actually, computing is used almost everywhere today, so having some knowledge of it is bound to come in handy. And did you know that software developers are among the most in-demand and highly-paid people today?)

So let's take a look at the code:

Lines 1 and 2 create two variables named right_side and left_side. These variables contain the values of the righthand side of the equation and the lefthand side. (Later on line 5 we will use the comparison operator (==) to check if these two quantites are equal or not.)

Line 3 has a for loop which is the perfect control flow structure for looping over a range of numbers. Control flow structures guide how the program flows from one statement to another; the flow can branch one way or another depending on comparisons.

  • In a for loop, you have to specify two things: a variable name, and a range.
  • We picked 'x' for the variable name because x is the variable we used in the equation we are trying to solve (at the top of the page).
  • The range we specified is (1, 30). We picked 1-30 because we think the answer is contained somewhere in that range. The range tells the for loop what numbers to plug into x. For each number in the range, the for loop executes all the indented lines of code nested below itself (lines 4-7). For example, it first makes x=1, then executes all the indented statements below until it hits the if statement on line 5. From there it either continues to line 6 if the if condition is true, or it goes back to line 3 and assigns x the next value (2) if the if condition is false, where it repeats the loop.
Line 4 is where it solves the lefthand side of the equation using the current value of x.

Line 5 is where it checks to see if the lefthand side equals the righthand side.

Now going back to line 3, the for loop will repeat the above steps until one of the following events occurs:

  • It either finds the answer (line 5 is true), prints it out (line 6), then exits (line 7). (The double-equal sign == tests whether it's true that the left side equals the right side. If it is true, line 6 is executed next. If not, control goes back up to the for and the value of x is incremented by 1.)
  • Or, it can't find the answer (line 5 is never true) and has exhausted all the numbers in its range and exits the loop (but not by reaching line 7). It would then begin executing a statement on line 8. (If it's never true, it's because the answer is not contained in the range we specified. For example, if we had specified the range to be (1, 5), it will never find the answer, because the answer is 6--outside the range. Or, if the answer was actually 6.5, it still wouldn't find it because our range is the integers) between 1-30.)
We're almost ready to enter the code into the Online Python tutor, but first a word about paying close attention to detail:

Computers do exactly what they're told. If you're code is correct, you'll get a correct answer. If your code is wrong, however, you'll either an error message and your program won't run, or you'll get the wrong answer. To avoid syntax errors that can prevent your program from running, study each line of code carefully. In the Online Python Tutor simulator, you'll see a red X next to lines that contain syntax errors. For example, if you forget a colon (:), that is a syntax error and your program won't run. Or, if you don't indent when you should, that's also an error and your program won't run. Logical errors (bugs) can be harder to detect. There will be no red X and your program will run, but your answer will be wrong. One common error is using the assignment operator (=) when you should be using the equality operator (==), which is used to test for a true or false condition. Another common error is not using parenthesis properly when grouping your terms. Example: the solution to 3x+6=24 is different than the solution to 3(x+6)=24.

Ok, let's copy the program to the Online Python Tutor and run it:

  • Write the JavaScript program down on a separate sheet of paper exactly as it appears above on lines 1-7, including indentations.
  • Open a new browser tab and copy-and-paste this web address: http://www.pythontutor.com/visualize.html#mode=edit
    (Then press Enter to actually go there.) You can switch back to this page as needed.
  • Click inside the box and start typing your program line-by-line. When you indent, use 4 spaces. (If it indents automatically, don't indent again. Python is one of the only programming languages that requires you to indent, which is good programming practice. But remember to be consistent in the number of spaces used.) Press Enter at the end of each line. Notice that on line 3 (after you typed-in while x < 30), the next line indents automatically. (If you copied-and-pasted from the example instead of typing it in, the indentation might be wrong, causing an error.)
  • After you've entered the last line and pressed the Enter key, click the Visualize Execution button. If there were no mistakes, your code will move into a box to the left and a red arrow will point to the first line. (If that didn't happen, start debugging!)
  • Click the Forward> button and watch your variables change in the blue box to the right as the arrow traces out the execution of your program. Your final answer will appear in the Program output box $tempAns.
  • Congratulations! You've just written your first Python program. :-)


Footnotes


1 Here are some ways to learn JavaScript on your own: w3schools.com, codeacademy, udacity. Besides Online Python Tutor and w3schools.com, another good site for experimenting with JavaScript (and HTML and CSS) is JSFIDDLE. Every bookstore has recent books on JavaScript, but libraries tend to have vastly outdated editions.