Variables and Arithmetic Operators in Javascript Naming Variables Declaring Variables Using Variables the Assignment Statement Arithmetic Operators
Total Page:16
File Type:pdf, Size:1020Kb
Topics Variables and Arithmetic Operators in JavaScript Naming Variables Declaring Variables Using Variables The Assignment Statement Arithmetic Operators 1 2 What Are Variables in JavaScript? Legal Identifiers in JavaScript Variables in JavaScript have the same Another name for a variable in JavaScript is an meaning as variables in algebra. That is, they identifier represent some unknown, or variable, value. Variables in JavaScript may be given representations containing multiple characters. x = a + b But there are rules for these representations. z + 2 = 3(y - 5) Legal variable names in JavaScript May only consist of letters, digits, and underscores Remember that variables in algebra are Can not have blank spaces represented by a single alphabetic character. May not begin with a number They are "containers" that hold values. 3 May not be a JavaScript reserved word (keyword) 4 Reserved Words (Keywords) in CMSC104 Naming Conventions JavaScript abstract delete function null throw For this class (and some future CS classes), boolean do goto package throws we’re going to use the following rules when break double if private transient naming variables: byte else implements protected true case enum import public try Begin variable names with lowercase letters catch export in return typeof Use meaningful names char extends instanceof short var Separate “words” within identifiers with underscores class false int static void or mixed upper and lower case. const final interface super volatile Examples: surfaceArea surface_Area continue finally long switch while surface_area debugger float native synchronized with Be consistent! default for new this 5 6 Case Sensitivity Legal Identifiers vs. Naming Conventions JavaScript is case sensitive It matters whether an identifier, such as a variable Legal identifiers refer to the restrictions name, is uppercase or lowercase. JavaScript places on naming identifiers, i.e. Example: variable names cannot begin with a number. area Area Naming conventions refer to the standards you must follow for this course, i.e. all AREA variable names must begin with lowercase. ArEa are all seen as different variables. 7 8 Which Are Legal Identifiers? Which follow the CMSC104 Naming Conventions? AREA 3D Area person1 lucky*** num45 Last_Chance values Last-Chance #values x_yt3 pi x_yt3 pi finaltotal numChildren num+ %done area_under_the_curve area_under_the_curve 9 10 Declaring Variables Declaring Variables (con’t) Before using a variable, you need to declare When we declare a variable it. Space is set aside in memory to hold the value The declaration statement includes the var That space is associated with the variable name keyword and the name of the variable. The initial value of the variable is undefined (it is not 0!) Examples of variable declarations: Visualization of the declaration var meatballs; var meatballs, area; var area; var meatballs ; meatballs undefined 11 name 12 More About Variables Using Variables: Initialization In JavaScript variables can hold four basic Variables may be be given initial values, or types of values initialized , when declared. Examples: Numbers length 7 i.e. 40, 15.5, 700 var length = 7; Strings diameter i.e. "Hello, World!", "Linux is cool!" var diameter = 5.9; 5.9 Booleans var message = "Hello!"; message i.e. true, false “Hello!” Null var walletEmpty = true; walletEmpty i.e. null true 13 14 Using Variables: Assignment Using Variables: Initialization Do not “hide” the initialization Variables may have values assigned to them through the use of an assignment statement . put initialized variables on a separate line a comment is always a good idea Such a statement uses the assignment operator = Example: This operator does not denote equality. It assigns the value of the righthand side of the statement (the var height; /* rectangle height */ expression ) to the variable on the lefthand side. var width = 6; /* rectangle width */ Examples: var area; /* rectangle area */ diameter = 5.9 ; area = length * width ; NOT var height, width = 6, area; Note that only single variables may appear on the lefthand 15 side of the assignment operator. 16 Brian’s Shopping Trip Revisited Pseudocode Display "Enter the price of the first item: " Problem : Brian bought a belt for $9 and a shirt Read <item 1 price > that cost 4 times as much as the belt. He Display "Enter the multiplier: " then had $10. How much money did Brian Read <multiplier > have before he bought the belt and shirt? Display "Enter the amount left after shopping: " Read <amount left > <item2 price > = < multiplier > X < item1 price > <start amount > = < item1 price > + < item2 price > + <amount left > Display "The starting amount was ", < start amount > 17 18 Example: Declarations and Example: Declarations and Assignments Assignments document.write("The cost of item 1: $"); <script type = "text/javascript"> document.write(item1Price); <!-- var item1Price, multiplier; document.write("<br />"); var amountLeft, item2Price; item1Price item2Price document.write("The multiplier: "); var startAmount; 9 undefined document.write(multiplier); multiplier startAmount document.write("<br />"); item1Price = 9; 4 undefined document.write("The money we had left: $"); multiplier = 4; amountLeft document.write(amountLeft); amountLeft = 10; 10 document.write("<br />"); document.write("The starting amount was: $"); item2Price = multiplier * item1Price; document.write(startAmount); startAmount = item1Price + item2Price + //--> amountLeft; </script> 19 20 (continued on next slide) Screenshot of Variables Example Enhancing Our Example What is the problem with our solution? It produces the same results every time! Let’s also ask the user to enter the values for our variables, rather than “hard-coding” them in. 21 22 Try it! http://userpages.umbc.edu/~dblock/variables1.html Screenshot of prompt() Getting User Input example Use the prompt() function Will display a pop-up window asking the user to enter data Examples: name = prompt("What is your name?"); payRate = prompt("Enter your pay rate: "); score = prompt("Please enter the score: "); The prompt() function is equivalent to the Display/Read in pseudocode. 23 24 Enhanced Variables Example Enhanced Variables Example <script type = "text/javascript"> <!-- document.write("The cost of item 1: $"); var item1Price, multiplier; document.write(item1Price); var amountLeft, item2Price; var startAmount; document.write("<br />"); document.write("The multiplier: "); item1Price = prompt("Please enter the cost of the first item: "); document.write(multiplier); item1Price = parseFloat(item1Price); document.write("<br />"); multiplier = prompt("Please enter the multiplier: "); multiplier = parseFloat(multiplier); document.write("The money we had left: $"); amountLeft = prompt("Please enter the amount left: "); document.write(amountLeft); amountLeft = parseFloat(amountLeft); document.write("<br />"); document.write("The starting amount was: $"); item2Price = multiplier * item1Price; document.write(startAmount); startAmount = item1Price + item2Price + //--> amountLeft; </script> 25 26 Changes Made to Include User Screenshot of Enhanced Input Variables Example Instead of giving the variables explicit initialization values, as in: item1Price = 9; multiplier = 4; amountLeft = 10; we used the following: item1Price = prompt("Please enter the cost of the first item: "); item1Price = parseFloat(item1Price); multiplier = prompt("Please enter the multiplier: "); multiplier = parseFloat(multiplier); amountLeft = prompt("Please enter the amount left: "); amountLeft = parseFloat(amountLeft); 27 28 Screenshot of Enhanced Screenshot of Enhanced Variables Example Variables Example 29 30 Final Screenshot of Enhanced Variables Example Good Programming Practices Place a comment before each logical “chunk” of code describing what it does. Do not place a comment on the same line as code (with the exception of variable declarations). Use spaces around all arithmetic and assignment operators. Use blank lines to enhance readability. 31 32 Try it! http://userpages.umbc.edu/~dblock/variables2.html Arithmetic Operators in Good Programming Practices JavaScript Place a blank line between the last variable Name Operator Example declaration and the first executable statement of the program. Addition + num1 + num2 Indent the body of the program 2 to 3 spaces Subtraction - initial - spent -- be consistent! Multiplication * radius * 2 Division / sum / count Modulus % m % n 33 34 Modulus Detailed Modulus Example The expression m % n yields the integer 17 % 5 = 2 remainder after m is divided by n. The whole number left Modulus is an integer operation -- both over (remainder) is the answer. operands MUST be integers. 3 Examples : 17 % 5 = 2 5 17 6 % 3 = 0 -15 9 % 2 = 1 R 2 5 % 8 = 5 35 36 Another Detailed Modulus Example Uses for Modulus 5 % 8 = 5 Used to determine if an integer value is even or odd The whole number left over (remainder) is the 5 % 2 = 1 odd 4 % 2 = 0 even answer. 0 If you take the modulus by 2 of an integer, a 8 5 result of 1 means the number is odd and a -0 result of 0 means the number is even. R 5 The Euclid’s GCD Algorithm (from the Algorithms 1 lecture) 37 38 Arithmetic Operators Rules of Operator Precedence Using Parentheses Use parentheses to change the order in which Operator(s) Precedence & Associativity an expression is evaluated. ( ) Evaluated first. If nested a + b * c Would multiply b * c first, (embedded) , innermost first. If then add a to the result. on same level, left to right. If you really want the sum of a and b to be * / % Evaluated second. If there are multiplied by c, use parentheses to force the several, evaluated left to right. evaluation to be done in the order you want. + - Evaluated third. If there are (a + b) * c several, evaluated left to right. Also use parentheses to clarify a complex = Evaluated last, right to left. expression. 39 40.