Variables and Arithmetic Operators in JavaScriptTopicsWhat Are Variables in JavaScript?Legal Identifiers in JavaScriptReserved Words (Keywords) in JavaScriptCMSC104 Naming ConventionsCase SensitivityLegal Identifiers vs. Naming ConventionsWhich Are Legal Identifiers?Which follow the CMSC104 Naming Conventions?Declaring VariablesDeclaring Variables (con’t)More About VariablesUsing Variables: InitializationSlide 15Using Variables: AssignmentBrian’s Shopping Trip RevisitedPseudocodeExample: Declarations and AssignmentsSlide 20Screenshot of Variables ExampleEnhancing Our ExampleGetting User InputScreenshot of prompt() exampleEnhanced Variables ExampleSlide 26Changes Made to Include User InputScreenshot of Enhanced Variables ExampleSlide 29Slide 30Final Screenshot of Enhanced Variables ExampleGood Programming PracticesSlide 33Arithmetic Operators in JavaScriptModulusDetailed Modulus ExampleUses for ModulusArithmetic Operators Rules of Operator PrecedenceUsing Parentheses1Variables and Arithmetic Operators in JavaScript2TopicsNaming VariablesDeclaring VariablesUsing VariablesThe Assignment StatementArithmetic Operators3What Are Variables in JavaScript?Variables in JavaScript have the same meaning as variables in algebra. That is, they represent some unknown, or variable, value.x = a + bz + 2 = 3(y - 5)Remember that variables in algebra are represented by a single alphabetic character.They are "containers" that hold values.4Legal Identifiers in JavaScript Another name for a variable in JavaScript is an identifierVariables in JavaScript may be given representations containing multiple characters. But there are rules for these representations.Legal variable names in JavaScriptMay only consist of letters, digits, and underscoresCan not have blank spacesMay not begin with a numberMay not be a JavaScript reserved word (keyword)5Reserved Words (Keywords) in JavaScriptabstract delete function null throwboolean do goto package throwsbreak double if private transientbyte else implements protected truecase enum import public trycatch export in return typeofchar extends instanceof short varclass false int static voidconst final interface super volatilecontinue finally long switch whiledebugger float native synchronized withdefault for new this6CMSC104 Naming ConventionsFor this class (and some future CS classes), we’re going to use the following rules when naming variables:Begin variable names with lowercase lettersUse meaningful namesSeparate “words” within identifiers with underscores or mixed upper and lower case. Examples: surfaceArea surface_Area surface_areaBe consistent!7Case SensitivityJavaScript is case sensitiveIt matters whether an identifier, such as a variable name, is uppercase or lowercase.Example:areaAreaAREAArEaare all seen as different variables.8Legal Identifiers vs. Naming Conventions Legal identifiers refer to the restrictions JavaScript places on naming identifiers, i.e. variable names cannot begin with a number.Naming conventions refer to the standards you must follow for this course, i.e. all variable names must begin with lowercase.9Which Are Legal Identifiers?AREA 3D lucky*** num45Last-Chance #valuesx_yt3 pinum$ %donearea_under_the_curve10Which follow the CMSC104 Naming Conventions?Area person1Last_Chance valuesx_yt3 pifinaltotal numChildrenarea_under_the_curve11Declaring VariablesBefore using a variable, you must you must declare it.The declaration statement includes the var keyword and the name of the variable.Examples of variable declarations: var meatballs; var area;12Declaring Variables (con’t)When we declare a variableSpace is set aside in memory to hold the value That space is associated with the variable nameThe initial value of the variable is undefined (it is not 0!)Visualization of the declaration var meatballs ; namemeatballs undefined13More About VariablesIn JavaScript variables can hold four basic types of valuesNumbersi.e. 40, 15.5, 700Stringsi.e. “Hello, World!”, “Linux is cool!”Booleansi.e. true, falseNulli.e. null14Using Variables: InitializationVariables may be be given initial values, or initialized, when declared. Examples:var length = 7 ;var diameter = 5.9 ;var message = “Hello!” ;var walletEmpty = true;75.9“Hello”lengthdiametermessagetruewalletEmpty15Do not “hide” the initializationput initialized variables on a separate linea comment is always a good ideaExample:var height; /* rectangle height */var width = 6 ; /* rectangle width */var area ; /* rectangle area */NOT var height, width = 6, area;Using Variables: Initialization16Using Variables: AssignmentVariables may have values assigned to them through the use of an assignment statement.Such a statement uses the assignment operator =This operator does not denote equality. It assigns the value of the righthand side of the statement (the expression) to the variable on the lefthand side.Examples:diameter = 5.9 ; area = length * width ;Note that only single variables may appear on the lefthand side of the assignment operator.17Brian’s Shopping Trip RevisitedProblem: Brian bought a belt for $9 and a shirt that cost 4 times as much as the belt. He then had $10. How much money did Brian have before he bought the belt and shirt?18PseudocodeDisplay "Enter the price of the first item: "Read <item 1 price>Display "Enter the multiplier: "Read <multiplier>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>19Example: Declarations and Assignments<script type = “text/javascript”> <!-- var item1Price, multiplier; var amountLeft, item2Price; var startAmount; item1Price = 9; multiplier = 4; amountLeft = 10; item2Price = multiplier * item1Price; startAmount = item1Price + item2Price + amountLeft;amountLeftmultiplieritem1Price9410 (continued on next slide)startAmountitem2Priceundefinedundefined20Example: Declarations and Assignments document.write("The cost of item 1: $"); document.write(item1Price); document.write("<br />"); document.write("The multiplier:"); document.write(multiplier);
View Full Document