1 / 23

CNIT 133 Interactive Web Pags – JavaScript and AJAX

CNIT 133 Interactive Web Pags – JavaScript and AJAX. JavaScript Variables. Agenda. My Web Site: http://fog.ccsf.edu/~hyip (download syllabus, class notes). Declare and initialize variables Variable naming rules Data types conversion NaN and isNaN The typeof operator. Variable.

halona
Download Presentation

CNIT 133 Interactive Web Pags – JavaScript and AJAX

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CNIT 133 Interactive Web Pags –JavaScript and AJAX JavaScript Variables

  2. Agenda • My Web Site: http://fog.ccsf.edu/~hyip (download syllabus, class notes). • Declare and initialize variables • Variable naming rules • Data types conversion • NaN and isNaN • The typeof operator

  3. Variable • A variable is a symbolic name that represents a value that can, and likely will, change or vary during a program’s execution. Physically, it is a storage place in memory that you can access using a symbolic name that you choose when you define or declare that variable. • When you declare a variable, the JS interpreter tells the computer to set aside space in memory to hold the value of your variable.

  4. Declaring Variables • In order to use a variable, you should first declare it and, preferably, initialize it. • It is good programming practice to declare and initialize a variable before using it in your program, JS does not require you to do so. • To declare a variable, you simply type the special keyword var, followed by a space and the name of your variable: var myVariable /* the value is undefined */ Var num1, firstName, isOn

  5. Initializing Variables • To initialize a variable is to assign it a default or starting value. • The best time to initialize a variable is when you declare it. var num1 = 37 var firstName = "Tina" var isOn = false var num1 = 37, firstName = "Tina", isOn = false; var visitor = promopt("What \’s your name? ", "");

  6. Variable Naming Rules • JS has a few rules for naming variables: • Only letters, numbers, and the underscore (_) are valid characters in a variable name. • Variable names may not begin with a number. They must start with a letter or an underscore (_). • Variable names may not contain spaces. • Reserved words may not be used as variable names. • Pre-defined object, property, method, and built-in function names are also off limits, for example, document, window, form, name, src, isNaN, etc.

  7. Variable Naming Rules (continue…)

  8. Variable Naming Rules (continue…) • One last note about naming JS variables: JS is case sensitive. • Thus, the names sitevisitor, SITEVISITOR, siteVisitor, SiteVisitor, are different variables.

  9. Evaluating Expressions • Expression evaluation is closely related to data values and variables. • To determine the value of a variable, you have to assess, calculate, or evaluate the expression that declare it or was later assigned to it. var num1 = 37; // num1 evaluates to 37

  10. Undefined Variable • zVar is "undefined" because it was never declared nor initialized. Using it results in a runtime error. <html> <head><title>Undefined Variable</title> </head> <body> <script language= "JavaScript " type= "text/javascript"> document.write(zVar); </script> </body> </html>

  11. Defined variable whose value is undefined • If an unassigned variable were formally declared using the var keyword, an evaluation of that variable would result in undefined. <html> <head><title>Undefined</title> </head> <body> <script language="JavaScript" type="text/javascript"> var zVar; document.write(zVar); </script> </body> </html>

  12. Dynamically Typed • JS is a loosely typed language. • You do not have to specify the data type of a variable when you declare it or before you use it. var guess = 37; // number guess = "white"; // string guess = true; // boolean guess = "pink"; // string guess = 22; // number • Because of this feature, Netscape describes JS as a “dynamically typed” language.

  13. Convert from Number to String • It is also easy to convert from one data type to another. • When a JS expression involving the plus or concatenation operator contains numbers followed by strings, JS automatically converts the numbers to string values before evaluating the expression. var result = 7 + "up"; // result: 7up result = "hi" + 5; // result: hi5 var num1 = 85; // initialize num1 as a numeric 85 num1 = num1 + ""; // num1 is a string

  14. Convert from String to Number • JS has two built-in functions: parseInt() and parseFloat(). • parseInt() parses only integers parseInt(“3 blind mice”); // 3 parseInt(“12.34 meters”); // 12 parseInt(“height is 5 ft”); // NaN • parseFloat() parses both integers and floating-point numbers. parseFloat(“3.14 meters”); // 3.14 parseFloat(“3 ft hight”); // 3 parseFloat(“$72.47”); // NaN

  15. Convert from String to Number - sample • HTML only provides a text box, such as prompt(). • Enter 10 for quantity; 9.95 for price • The result is 99.5 (ok). <html> <head><title>prompt</title> </head> <body> <script language="JavaScript" type="text/javascript"> var qty = prompt("Enter quantity", ""); var price = prompt("Enter price", ""); Alert("Your total is: " + qty * price); </script> </body> </html>

  16. Convert from String to Number – No Conversion • Enter 15 for first number, 22 for second number. • Sum is 1522 (wrong) <html> <head><title>Sum</title> </head> <body> <script language="JavaScript" type="text/javascript"> var num1 = prompt("Enter first number", ""); var num2 = prompt("Enter second number", ""); Alert("Sum is: " + (num1 + num2)); </script> </body> </html>

  17. Convert from String to Number – No Conversion (continue…) • Use parseInt() or parseFloat() to fix the problem. var num1 = parseFloat(prompt("Enter first number", "")); var num2 = parseFloat(prompt("Enter second number", "")); OR alert("Sum is: " + (parseFloat(num1) + parseFloat(num2))); • Now the SUM is 37

  18. NaN • NaN is a special keyword that indicates the value is not a number. • Display NaN <html> <head><title>NaN</title> </head> <body> <script language="JavaScript" type="text/javascript"> var guess = "white"; document.write(parseFloat(guess)); </script> </body> </html>

  19. NaN & isNaN() • To display message: Not a number instead of NaN • Output: Guess: NaN (No error message) <html> <head><title>NaN</title> </head> <body> <script language= "JavaScript" type= "text/javascript" > var guess = "white"; var newGuess = parseFloat(guess); document.write("Guess: ", guess, "<br>"); if (newGuess == NaN) // if newGuess is equal to NaN { document.write("It is not a number.", "<br>"); } </script> </body> </html>

  20. NaN & isNaN() (continue…) • isNaN() is a built-in function to see if an expression evaluates to NaN or not. • Use isNaN() to fix the previous problem. <html> <head><title>NaN</title></head> <body> <script language= "JavaScript" type= "text/javascript" > var guess = "white"; var newGuess = parseFloat(guess); document.write("Guess: ", guess, "<br>"); if (isNaN(newGuess)) // if newGuess is equal to NaN { document.write("It is not a number.", "<br>"); } </script> </body> </html>

  21. The typeof Operator • The typeof operator determines the current data type of any variable. • The result of a typeof operation are “number” “string” “boolean” “object” “undefined” • The syntax is typeof (operand) typeof operand • Operand is the variable, object, object property, literal, or special keyword (null, undefined, etc) whose type you wish to know • NOTE: the parentheses are optional, but it is considered good programming style to use them.

  22. Possible values returned by the typeof operator <html> <head><title>Typeof </title> </head> <body> <script language="JavaScript" type="text/javascript"> var myNum = 7; var myWord = "oh, my!"; var answer = false; var today = new Date(); var notDefined; var noValue = ""; document.write("<b>Variable: Typeof: </b><br>" ); document.write("myNum: " , typeof(myNum), "<br>" ); document.write("myWord: ", typeof(myWord), "<br>"); document.write("answer: ", typeof(answer), "<br>" ); document.write("today: ", typeof(today), "<br>"); document.write("document: ", typeof(document), "<br>"); document.write("notDefined: ", typeof(notDefined), "<br>"); document.write("noValue: ", typeof(noValue), "<br>"); document.write("undefined: ", typeof(undefined), "<br>"); document.write("null: ", typeof(null), "<br>"); document.write("NaN: ", typeof(NaN), "<br>"); document.write("undeclared: ", typeof(undeclared), "<br>"); document.write("document.bgColor: ", typeof(document.bgColor), "<br>" ); </script> </body> </html>

  23. Tips avoid JS dynamic data typing • Declare all variables before using them with the keyword var, preferably at the beginning of your program. • Use descriptive names when defining your variables • Initialize all variables and try to stick to the initial data type throughout your program. • Describe each variable with a brief comment when you declare and initialize it. • When in doubt about whether JS will convert a string to a number for your or not, perform the conversion yourself. • Always convert form field entries and prompt box responses for which you expect numeric input into numbers with parseInt() or parseFloat(), and test the result of these operations with isNaN() before performing any mathematical operations.

More Related