Chapter 3 - Simple JavaScript - Programming Basics Lesson 1 - JavaScript: What is it and what does it look like? PP presentation JavaScript.ppt. Lab 3.1. Lesson 2 - JavaScript Comments, document.write(), and document.writeln() Like HTML, JavaScript supports comments. In fact, JS comments come in two forms: - JS line comments follow two forward slashes //. - JS block comments begin with /* and end with */. Example: JSCommentsWrite.html. Writing (printing) in JS is accomplished with the document.write() and document.writeln() methods. - The document object represents the contents of the browser s window. - We use the document object with the write() and the writeln() methods. - The write() and writeln() methods take a text string as an argument. The argument is enclosed in quotation marks. - writeln() adds a carriage return after its text argument. write() does not. Example: JSCommentsWrite.html. Note the <PRE>...</PRE> tags. Lab 3.2. Lesson 3 - Variable Assignments and Expressions variable - a value stored in a computer. A variable can be thought of as a container that holds things like numbers and letters. The particular value a variable stores can change. That s why it s called a variable! The notion of a variable in computing is exactly the same as variable in mathematics. For example, if x = 4, then 3 + x = 7, and so on. In a program, you should give variables names which suggest what they stand for. Using simply x for a variable isn t very descriptive. Instead, use something like totalcost or total_cost There are some rules and conventions you need to observe when naming variables. - Variable names must begin with a letter or a $ or an _. In particular, a variable name CANNOT begin with a number. - A common practice is to use words to describe the variable with either an _ separating the words or the first word starting in lower case and subsequent words capitalized. - Certain words are reserved and may not be used as names of variables. - Recall that JavaScript is case sensitive. paycheck and PAYCHECK and Paycheck and paycheck and PaYcHeCk are all different variables. - Variable names may not contain spaces.
Variables are declared by using the var keyword. For example, var paycheck = 1200; In addition to being a number, a variable can also be a sequence of characters or a string. For example, var myname = "Jim"; (Note the quotation marks.) data type - the type of information a variable carries. JavaScript has four data types: - number - a whole number or a decimal. - logical or boolean - the logical values true or false. The name boolean comes from George Boole, a 19th century mathematician who developed some of the theories of mathematical logic. - string - text. - null - an empty value. JavaScript is a loosely typed programming language in the sense that you do not (and are not allowed to) declare variables by type. Moreover, the type of a variable can change throughout a program. On the other hand, Java is a strongly typed programming language. Examples: NumberVariables.html and StringVariables.html. Be sure to read the discussion in Lesson 3 about operators and expressions. A list of basic operators with examples is given in the table. expression - a combination of values, variables, and operators which can be evaluated. An operator can be classified by the type of operation it performs. arithmetic operators - the operators +, -, *, /, % used for ordinary arithmetic. comparison operators - the operators <, <=, >, >=, == used to compare two quantities. Note that == and not the assignment operator = is used to test for equality. assignment operators - operators used to assign values to variables. There are several assignment operators, but the only one we use is =. - In programming, you have to understand that = is an assignment operator. - For example, a statement such as i = i + 1; is mathematically incorrect if viewed as an equation, but it is a correct programming statement. What happens is that 1 is added to the current value of i and the result is assigned as the new value of i. - For another example, the statements var x = 5, y = 8; x = x + y; result in x having the value 13. logical operators - next lesson. Lab 3.3. Lab 3.4.
Lesson 4 - Control Structures Up to now, the flow control in a JavaScript program has been simple; actions were performed in the order they were written down. We now look at how to write programs with more complicated flow control. The ability to alter the flow control adds a whole new dimension to the types of programs you can write. if and if-else Statements In programs, just as in everyday life, things can sometimes go in one of two different ways. For example, if you have money in a checking account, your bank might pay you a little interest. On the other hand, if your checking account is overdrawn, your bank might charge you a penalty that will make your negative balance even more negative. This could be reflected in the bank s accounting program by the following if-else statement: balance is a variable containing your checking-account balance. INTEREST_RATE is a constant equal to the bank s interest rate. OVERDRAWN_PENALTY is a constant equal to the bank s overdrawn penalty. if (balance >= 0) balance = balance + (INTEREST_RATE * balance)/12; else balance = balance - OVERDRAWN_PENALTY; The meaning of this if-else statement is just the meaning it would have if it was read as an English sentence. When your program executes an if-else statement, it first checks the expression in the parentheses after the if. If this expression is true, the first command block of statements is executed; otherwise, the command block of statements after the else is executed. In the example, if balance is positive or zero, the first command block is executed to include interest. If balance is negative, the second command block is executed to subtract the penalty. Remark: If the command block of statements contains more than one statement, you have to use braces. Example: BankBalance.html. If you omit the else part of an if-else statement, then you have an if statement. In this case, if the expression in parentheses after the if is true, the command block after the if is executed; otherwise, the command block is skipped and execution of the program continues after the command block. In the example, your bank might not charge a penalty for overdrawn accounts. Then all you need is the following if statement: if (balance >= 0) balance = balance + (INTEREST_RATE * balance)/12;
Conditional Expressions The conditional expression in an if or if-else statement can involve both comparison and logical operators. We already discussed comparison operators, the operators <, <=, >, >=, == used to compare two quantities. Note that == and not the assignment operator = is used to test for equality. logical operators - operators used to compare two boolean quantities. There are three logical operators: && (and) (or)! (not) To understand how these logical operators work, it helps to know their truth tables. P && Q P Q!P Q true false Q true false P P P!P true true false true true true true false false false false false true false false true Example: If a = 2 and b = 3, then a == 2 && b == 4 is false and a == 2 b == 4 is true. Lab 3.5. Explain JavaScript s built-in alert() and prompt() functions. Quiz1.html. while Statements loop statement - a statement that repeatedly executes a statement or block of statements as long as a condition is true. Example: BuckleShoe.html. Note that the while loop includes a counter called count. counter - a variable which is incremented or decremented during each iteration of a loop. A counter is needed to guarantee that the while statement will eventually terminate. Otherwise, an infinite loop occurs and the while loop goes on forever. If an infinite loop occurs, you have to force the Web browser to quit. During each pass through the while statement, we increment the counter by 1 so that the condition in the while statement will eventually be false and the while statement ends. We can decrement as well as increment a counter. Example: BlastOff.html. Lab 3.6. You might want to look at the example in Lesson 4 first. Lesson 5 - Functions and External JavaScript Files function - a collection of statements designed to perform a particular task. parameter or argument - the input variable(s) to a function.
Like variable, the notion of function in computing is the same as function in mathematics. For example, if y = f (x) = 3x 2 +1 and if x = 2, then y = f (2) = 3 2 2 +1=13. x is the parameter or argument for the function. A function may or may not return a value. For example, a function that computes something like an average would return a value. A function that only prints something wouldn t return a value. A function need not have parameters. For example, a function that always prints the same message doesn t need any parameters. A function is defined using the function keyword. The general syntax is: function functionname(parameter1, parameter2,...) { statement1; statement2; (Note the opening and closing {}.)... } Naming functions follows the same rules and conventions as naming variables. A function is executed or called or invoked by including its name and any appropriate parameters in a subsequent JavaScript statement. Functions should be defined in the <HEAD> section, and function calls should be placed in the <BODY> section. Examples: - PrintingFunction.html. - AverageFunction.html. - NoArgsFunction.html. A reminder about JavaScript s built-in alert(), confirm(), and prompt() functions. Variable Scope When you use a variable in a JavaScript program, you need to be aware of its scope. scope - where in a program a variable can be used. global variable - a variable declared outside any function definition; it can be used anywhere in a program. local variable - a variable declared inside a function definition; it can be used only within the function definition. Example: Scope.html. Lab 3.7. Lab 3.8. External JavaScript Files JavaScript is often incorporated directly into an HTML document, as we have been doing. You can also save JavaScript code in an external source file with a.js file extension. The SRC attribute in the <SCRIPT> tag is used to specify the name of the external source file. JavaScript source files cannot include HTML tags. You can use both internal and external JavaScript code. However, each JavaScript section must be included in a separate <SCRIPT>...</SCRIPT> tag pair.
Example: TwoJS.html and External.js. Where to put your JavaScript code: - When do you put JavaScript code directly in an HTML document and when do you use an external file? - If your JavaScript code is fairly short, it s usually easier to include the code directly in the HTML document. - For longer JavaScript code, it s easier to put the code in a.js source file. Advantages of an external file: - Your HTML document will be neater. - The JavaScript code can be shared among multiple HTML documents. - JavaScript code in an external source file is hidden from incompatible browsers. - JavaScript code in an external source file is hidden from other programmers. Code in an HTML document can be viewed.