## CS 131: Online Lesson Summaries

 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33

### Lesson 2: Algorithms and JavaScript

• An algorithm is a clear, step-by-step sequence of instructions for performing some task.
• In order for an algorithm to be well-defined, its steps must be clear and unambiguous to its intended executor.
• Programming is the process of designing algorithms whose intended executor is the computer.
• While spoken languages such as English and Spanish are rich and flexible, computers require more restricted and unambiguous programming languages such as JavaScript.
• The syntax of a language is the set of rules which specify how expressions in that language are to be formed. As such, typographical errors which violate these rules are known as syntax errors.
• Even the simplest syntax errors in a JavaScript program can cause execution to fail. Fortunately, the JavaScript interpreter displays error messages which help to identify errors in the code.

### Lesson 3: Displaying Values and Expressions

• The simplest means of displaying values in JavaScript is the document.write statement.
• By including the HTML tag <BR> in the message to be written, a line break will be appear in the output.
• Numerous other HTML tags can be included in output values in order to format them, such as <B></B>, <I></I>, <U></U>, <BLINK></BLINK>, and <FONT COLOR='red'></FONT>.
• JavaScript has three basic data types: strings, numbers, and booleans.
• The basic arithmetic operators '+' (addition), '-' (subtraction), '*' (multiplication), '/' (division), and '%' (remainder) are provided for numbers.
• In JavaScript, multiplication and division have higher precedence than addition and subtraction. Among operators with the same precedence, expressions are evaluated in a left-to-right order.
• For readability, JavaScript uses scientific notation to display very small and very large numbers.
• Since computers only have a finite amount of memory, there is a limit to the range of numbers that can be represented in JavaScript. Roundoff may occur on numbers with many significant digits.
• Strings can be concatenated (i.e., joined end-to-end) using the '+' operator.
• When the + operator is applied to a string and a number, the number is automatically converted into a string and then the two are concatenated.

### Lesson 4: Variables & Assignments

• A variable is a name that is used to represent some unspecified value in an expression.
• In JavaScript, a variable name can be any sequence of letters, digits, and underscores starting with a letter. Since JavaScript is case-sensitive, capitalization matters.
• Each JavaScript variable has a corresponding memory cell which stores its value. A value is assigned to a variable (and thus stored in the corresponding memory cell) using the assignment operator '='.
• When evaluating an assignment, the expression on the right-hand side is evaluated first, and the resulting value is then stored in the memory cell corresponding to the variable on the left-hand side.
• Any attempt to write or use a variable in an expression without first assigning it a value will result in an error.

### Lesson 5: Predefined Functions

• Mathematically speaking, a function is a mapping from some number of inputs to a single output. From a programming perspective, a function is a unit of computational abstraction.
• JavaScript provides an extensive library of predefined mathematical functions, including square root (Math.sqrt), absolute value (Math.abs), maximum (Math.max), minimum (Math.min), round down (Math.floor), round up (Math.ceil), round to the nearest integer (Math.round), and raise to a power (Math.pow).
• The random number function (Math.random) is an example of a function with no inputs. Each call to random returns a random number from the range [0,1).
• The predefined function prompt can be used to read a value from the user via a dialog box. The function takes two arguments, a prompt message and a default value. It returns the value entered by the user (or the default value if they don't enter anything).
• The prompt function always returns a string. A numeric string can be converted to its number value using the predefined parseFloat function.

### Lesson 6: Turtle Graphics

• "Turtle graphics" were developed for the language LOGO as a tool for helping beginning programmers visualize the effects of their actions.
• In a turtle graphics environment, the programmer draws figures by controling a "turtle" which leaves a trail on the screen as it moves.
• The turtle can be made to move relative to its current position using forward and backward. It can be made to turn relative to its current heading using left and right.
• The home function returns the turtle to the center of the screen, facing straight up.
• The erase function erases the current contents of the screen.
• The turtle can be made to move to a specific location using moveTo. Similarly, it can be made to turn to a specific heading using turnTo.
• You can control whether the turtle leaves a trail as it moves by calling penUp and penDown.
• The drawString function will display a string at the current location of the turtle.
• The current state of the turtle can be accessed using the functions getX, getY, getHeading, and getPen.

### Lesson 8: Abstraction & Functions

• Abstraction is the act of ignoring certain details and focusing on the general characteristics or features of a problem.
• In programming, functions abstract away the details of a particular computation, allowing the programmer to perform the computation without having to understand the process.
• Functions simplify the programmer's task by (1) minimizing the amount of detail the programmer must keep track of, and (2) minimizing the size and complexity of the resulting code.
• In JavaScript, the programmer can extend the abstractions provided by the language through user-defined functions.
• The general form of a simple JavaScript function definition is as follows: function FUNCTION_NAME(PARAMETERS) // Given : DESCRIPTION OF ASSUMPTIONS MADE ABOUT PARAMETERS // Returns: DESCRIPTION OF VALUE RETURNED BY FUNCTION { return EXPRESSION_SPECIFYING_FUNCTION_VALUE; }
• A function parameter is a variable that corresponds to the argument in the function call.
• If a function has multiple parameters, they are matched with arguments in the function call according to order: the first parameter matches the first argument, the second parameter matches the second argument, and so on.
• Complex problems can be solved by building simple abstractions on top of each other.
• In JavaScript, it is possible to have function which do not return a value. Instead, these functions are called for their side effects (e.g., document.write displays a value on the screen).

### Lesson 9: Function Calling Sequence

• The general form for function definitions is as follows: function FUNCTION_NAME(PARAMETER_1, PARAMETER_2,..., PARAMETER_n) // Given : DESCRIPTION OF ASSUMPTIONS MADE ABOUT PARAMETERS // Returns: DESCRIPTION OF VALUE RETURNED BY FUNCTION { var LOCAL_1, LOCAL_2,..., LOCAL_m; STATEMENTS return EXPRESSION_SPECIFYING_FUNCTION_VALUE; } where the function name, parameters, local variables, statements, and function value will differ depending on the task at hand.

• The calling sequence for functions is as follows:

1. The arguments in the function call are evaluated.
2. Execution shifts to the function being called.
3. Memory cells are allocated (created) for each parameter in the function, and the values of the corresponding arguments are assigned to these memory cells.
4. Memory cells are allocated (created) for each local variable.
5. The statements in the body of the function are executed in order.
6. When a return statement is encountered, the expression is evaluated.
7. Memory cells associated with the local variables are deallocated (destroyed).
8. Memory cells associated with the parameters are deallocated (destroyed).
9. Upon return, the value of the expression in the return statement replaces the function call in whatever expression it appears in.

• A parameter variable exists only inside the function. The associated memory cell is allocated (created) when the function is called, and deallocated (destroyed) when the function terminates.
• Local variables can be declared inside a function in order to store temporary values. Like parameters, local variables exist only inside the function.
• Parameters and local variables are independent of any external variables of the same names. That is, any reference to a variable name inside a function refers to the parameter or local variable for that function, not some external variable.
• Every variable that appears in a function should be either (1) a parameter to that function, or (2) declared as a local variable, BUT NOT BOTH.

### Lesson 10: Abstraction & Libraries

• Useful function definitions can be stored in separate files, called libraries, and loaded directly into the JavaScript interpreter.
• A library is loaded into the interpreter by specifying its name in the box labeled "Files (if any) to be included". When the "Execute Code" button is clicked, the function definitions in that library file are automatically loaded into the interpreter and can thus be called in subsequent code.
• The library random.js has been provided for you. It contains the following function definitions: function randomReal(low, high) // Given : low <= high // Given : a random real number in the range [low, high) function randomInt(low, high) // Given : low <= high // Given : a random real integer in the range [low, high] function randomChar(str) // Given : str is a nonempty string // Returns: a random character from the string function randomItem(list) // Given : list is a nonempty list (array) // Returns: a random item from the list

### Lesson 11: Repetition & For Loops

• A for loop can be used to execute a statement or sequence of statements some specified number of times.
• The general form of a simple for loop is the following: for (LOOP_VARIABLE = 1; LOOP_VARIABLE <= NUMBER_OF_REPS; LOOP_VARIABLE++) { STATEMENTS_TO_BE_REPEATED }
• The loop variable in a for loop can be any legal JavaScript variable. When no meaningful name is obvious, the variable names i, j, and k are commonly used.
• Indenting the statements that are inside the for loop improves readability since it makes it very clear where the loop begins and ends.
• As is the case with all variables in a function (excluding parameters), the loop variable in a for loop should be declared as a local variable.

### Lesson 12: For Loops & Sums

• Each execution of the code inside a for loop is known as a pass through the loop.
• Inside a for loop, it is possible to access the loop variable. The first time that the code is executed the loop variable has value 1, the second time the loop code is executed it has value 2, and so on up to the final number of repetitions.
• Accessing the value of the loop variable is especially useful when generating tables of data.
• The tags <SUP> and </SUP> are used to denote superscripted output.
• A variable can be used to maintain a running sum of values by first initializing the variable to 0, and then repeatedly adding new values to the sum.
• Assignments of the form sum = sum + newValue; are useful in updating the values of sum variables. Here, a newValue is added to the current value of sum, and then the updated value is reassigned to sum.

### Lesson 15: Conditional Execution & If Statements

• Conditional execution refers to the ability to execute a statement or sequence of statements only if some condition holds. In JavaScript, conditional execution is performed using if statements.
• The general form of an if statement is as follows, where the else case is optional: if (BOOLEAN_TEST) { STATEMENTS_IF_TRUE } else { STATEMENTS_IF_FALSE } If the boolean test evaluates to true, then we say that the test succeeds and so the code immediately below (inside the curly-braces) is executed. If the test evaluates to false and there is an else case, then the code below the else (inside the curly-braces) is executed.
• The following relational operators can be used to build boolean expressions: == equal to, != not equal to, < less than, <= less than or equal to, > greater than, and >= greater than or equal to.
• Arbitrary numbers of alternative cases can be considered using a cascading if statement, which is really nothing more than nested if statements. if (TEST_1) { STATEMENTS_IF_TEST_1 } else if (TEST_2) { STATEMENTS_IF_TEST_2 } else if (TEST_3) { STATEMENTS_IF_TEST_3 } . . . else { STATEMENTS_IF_ELSE }
• Since control statements are just like any other statement, you can nest one control statement inside another. For example, you can have an if statement inside a for loop, and vice versa.

### Lesson 16: If Statements & Counters

• A variable can be used to maintain a running count of the number of times some desired event happens (e.g., dice roll of 7, identical coin flips). Such a variable is known as a counter.
• A counter variable must first be initialized to 0, and then incremented each time the desired event happens.
• The increment operator ++ can be used to add one to the value of a variable. For example, the statement count++ is equivalent to the assignment count = count + 1.

### Lesson 17: Repetition & While Loops

• A while loop is a control statement that allows for conditional repetition. It combines the repetitiveness of for loops with the conditional control of if statements.
• The general form for a while loop is as follows: while (BOOLEAN_TEST) { STATEMENTS } If the loop test succeeds (evaluates to true), then the statements inside the loop body (inside the curly-braces) are executed. After making a pass through the loop, the loop test is re-evaluated, and the process repeats until the loop test finally fails (evaluates to false).
• Even though they look similar, while loops and if statements are very different control statements -- an if statement will execute its statements either once or not at all, whereas a while loop can execute its statements repeatedly.
• Infinite loops (or black hole loops) are while loops that repeat forever. The most common cause of infinite loops is failing to affect the loop test from inside the loop.
• Generally speaking, you should use a for loop whenever unconditional repetition is needed, and a while loop whenever conditional repetition is needed. In reality, however, a for loop is merely a while loop repackaged to make unconditional repetition clearer.

### Lesson 18: While Loops & Boolean Expressions

• Input verification is a common use of while loops. Verifying user input requires a conditional loop since you cannot predict how many tries it will take the user to enter the correct type of input.
• The logical connective OR (||), AND (&&), and NOT (!) can be used to build more complex boolean expressions.
• An expression involving OR evaluates to true if either of its components evaluates to true. For example, ((x < 0) || (x > 100)) will evaluate to true if either (x < 0) or (x > 100).
• An expression involving AND evaluates to true if both of its components evaluates to true. For example, ((x >= 10) && (x <= 20)) will evaluate to true if either (x >= 10) and (x <= 20).
• An expression involving NOT evaluates to the opposite of its component value. For example, ( !isNaN(x) ) will evaluate to true if isNaN(x) evaluates to false, and vice versa.
• When evaluating boolean expressions involving AND and OR, the JavaScript interpreter uses short-circuit evaluation, meaning that evaluation discontinues as soon as the final value of the expression can be determined.

### Lesson 19: Program Design

• Iterative refinement is an approach to program design in which a general outline of the problem solution is incrementally refined, adding more and more detail until the final program is derived.
• An incremental approach to program design can help in managing the complexity of large programs.
• In general, iterative refinement can be applied in the following way:
1. Describe a general solution to the problem in English. That is, identify the major tasks that must be accomplished and fit together to solve the problem.
2. Identify programming constructs that will perform the tasks identified in your English description.
3. Begin coding your solution by placing the control statements together to form a framework.
4. Fill in the details, little by little.

### Lesson 22: Dynamic Web Pages via JavaScript

• JavaScript code can be embedded in HTML documents and executed simply by loading the page into the browser.
• The tags <SCRIPT LANGUAGE="JavaScript"> and </SCRIPT> are used to denote JavaScript code that should be executed by the browser.
• The output produced by executing the JavaScript code is displayed on the Web page at the corresponding location.
• It is possible to load libraries of JavaScript code using the SRC attribute of the SCRIPT tag, e.g., <SCRIPT LANGUAGE="JavaScript" SRC="random.js"></SCRIPT>
• Function definitions (as well as library loads) should be placed in the HEAD of a page so that they will be loaded first.

### Lesson 23: Dynamic Images via JavaScript

• Images may be included in a Web page by including an IMG element in the HTML code.
• An IMG element must have a SRC attribute specifying the source file for the image. It may also have an ALIGN attribute specifying how that image is to be aligned with respect to adjacent text.
• JavaScript can be used to output HTML elements such as IMG. Since these elements are dynamically generated by the JavaScript code, it is possible to produce different elements each execution and so display different images each time the page is loaded.
• Single-quotes can be used to delineate strings as well as double-quotes. For example, 'foo' and "foo" are equivalent.

### Lesson 24: Event-Driven Programming

• Many Web pages are event-driven, reacting to events such as mouse clicks or keyboard entries. The actions to be taken when events occur are specified using JavaScript.
• The simplest event handler is a button, which specifies an action to take place when the mouse is clicked on that button. A button element looks like the following: <INPUT TYPE="button" NAME="ButtonName" VALUE="ButtonLabel" ONCLICK="JavaScriptCode">
• Buttons and other event-driven elements must be grouped inside form elements.
• Values can be read in from the Web page using text boxes. A text box element looks like the following: <INPUT TYPE="text" NAME="TextInputName" VALUE="InitialText">
• The contents of a text box can be accessed as: document.FORM-NAME.TEXT-BOX-NAME.value
• Similarly, values can be displayed in a text box by assigning the value of that text box, e.g., ONCLICK="document.EventForm.userName.value='Dave';"
• While a text box is limited to a single line of text, a text area can contain any number of lines. A text area element looks like the following: <TEXTAREA NAME="TextInputName" ROWS=NumRows COLS=NumCols WRAP="virtual"> Initial Text </TEXTAREA>

### Lesson 29: JavaScript Strings

• A software object is a structure which models an object in the real world.
• An object encompasses data (attributes) along with the operations (functions) that are to be performed on that data.
• In JavaScript, strings are objects with numerous predefined attributes and functions.
• the length attribute identifies how many characters are in the string
• the charAt function returns the character stored at a particular index of a string
• the indexOf function returns the index of the first occurrence of a substring within a given string
• the substring function returns a part of a string, specified by start and end indices
• the toUpperCase function returns the string with all lower-case letters replaced by their upper-case equivalents
• the toLowerCase function returns the string with all upper-case letters replaced by their lower-case equivalents
• Attributes and functions associated with an object are accessed by placing a period after the object, followed by the attribute or desired function call. For example, str.length will return the number of characters in str, while str.charAt(0) will return the first character in str.

### Lesson 30: JavaScript Strings & Page Design

• By embedding JavaScript programs in HTML code, the attractive and intuitive user-interface of the Web can be used by the programs.
• Care must be taken when designing Web pages so that the interface does not detract from the ease of use of the underlying JavaScript program.
• The picture displayed by an image element can be changed by assigning a new picture file to the src attribute of the image element.