Understanding JavaScript Data Types and Parsing

javascript n.w
1 / 24
Embed
Share

Learn about JavaScript data types, parsing data, and important concepts like arguments and working with strings, integers, and floats. Explore the essential aspects of programming through this comprehensive lecture.

  • JavaScript
  • Data types
  • Parsing
  • Programming concepts
  • Arguments

Uploaded on | 0 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.

E N D

Presentation Transcript


  1. JavaScript Data Types Parsing Data

  2. Learning Objectives By the end of this lecture, you should be able to: Explain what is meant by the term "argument". Identify the three "data types" that we will discuss through the remainder of the course. Recognize how and when to apply the parseInt() and parseFloat() functions. Recognizing when not to use the parse functions. Learning about programming by studying other people s code.

  3. Important & Challenging Lecture Ahead! This lecture may seem a bit esoteric, but please be aware that this material is important. Several concepts introduced here will be used throughout the remainder of the course, and will be heavily represented on your exams. This is not a very difficult lecture, but it will definitely require a little bit of review and mental effort. So please do not brush off this topic, and instead, give it your all! 3

  4. "Arguments" In programming, one term with which we should be familiar is: argument. An argument is the information you provide to a function when you invoke it. Some functions require 0 arguments, others may require 1 argument, and others can require multiple arguments. This is a very simple term, but it is important that you are comfortable using it. For example: alert('Hi'); Math.sqrt(23.7); Math.pow(3,4); Date(); --> the string 'hi' is the argument --> 23.7 is the argument --> this function has two arguments: 3 and 4 --> this function has 0 arguments 4

  5. Brief review: The + operator For each of the examples below, determine what value will result after applying the '+' operator. "Scooby" + "Doo" "ScoobyDoo (two strings, therefore, concatenation) "5" + "6" "56" (also two strings, therefore, concatenation) 5 + 6 11 (two numbers, therefore addition) What about the following? "5" + 6 "56" 6 + "foo" "6foo Recall that the moment you 'add' a string to anything -- including numbers -- the + operator will do concatenation. 5

  6. Data Types In many programming languages, every piece of data that we work with has a data type . There are many different data types out there, but in this course, we will focus on three. The three data types you should be able to name: Strings you are already familiar with these! Integers numbers that are whole (i.e. without a decimal) Floats numbers that have a decimal Examples: x = "25" x = 25 x = 25.0 x is holding a String x is holding an Integer x is holding a Float 6

  7. Examples In each of the four assignment statements below, identify the value and data type that will be stored inside the variable number: var x1 = "25"; var x2 = 10; var x3 = 5.3; var number; number = x1 + x2; Value: "2510" Data type: string number = x1 + x3; Value: "255.3" Data type: string number = x2 + x3; Value: 15.3 Data type: float number = x2 + 4; Value: 14 Data type: int In the first two cases, we have a string on one side of the + operator. Recall that the moment a string is present on either side, we will get concatenation. The third and fourth examples involve two numbers. In these case, then, the + operator will do addition. 7

  8. Fascinating um, who cares? All of this turns out to be hugely relevant in programming. For our purposes, the key point is what happens when we retrieve information from a form. IMPORTANT: Recall that all information retrieved from a form comes back as a string. Can you predict the output resulting from the following code? var age = document.getElementById('txtAge').value; //let's say the user entered 35 in the form var nextYear; nextYear = age+1; alert("Next year you will be " + nextYear + " years old."); Answer: The formula age+1 will evaluate to "351"! The reason is that the variable age that we retrieved from the form came back as a string. So, when we wrote: nextYear = age+1; we were adding a string to the number 1. As a result we ended up with concatenation. This is important stuff -- you can definitely expect exam question(s) relating to this! 8

  9. Recap & next steps: Let's return to the same example and see what we need to do to make things work the way we want them to. var age = document.getElementById('txtAge').value; //let's say the user entered 35 in the form //Since all values from a form come back as strings, // age is holding the string "35" var nextYear; nextYear = age+1; //Since age is holding a string, //we will get concatenation here alert("Next year you will be " + nextYear + " years old."); //will output "351" As discussed, when we typed: nextYear = age+1; we got concatenation since age was holding a string. Hopefully it is clear that in this particular situation, we really want is for the '+' operator to do addition -- not concatenation! What we need, then, is a way to convert the string "35" to the integer 35 . 9

  10. The parseInt() function JavaScript includes a very useful function that specializes in converting strings into integers. This function is called parseInt(). parseInt() accepts a piece of information (typically a string) inside its parentheses. (This piece of information is the "argument" that we discussed earlier). The parseInt function then attempts to convert that information into an integer. If the information inside the parentheses looks like an number, then great! If the information inside the parentheses does not look like a number, however, your script will generate an error and your page will not display properly. 10

  11. parseInt Examples Can you predict what will be stored inside the variable temp in each of the following examples? 1. 2. 3. 4. var temp; temp = parseInt("352"); temp = parseInt(49.99); temp = parseInt("ten"); Line 2? tempwill store the integer 352 The parseInt function has no difficulty converting this particular string to an int Line 3? tempwill be assigned the integer 49 The parseInt function has no difficulty converting this float to an int Important: Note that parseInt() does not round numbers up or down. Rather, the function simply chops off the decimal. We have a fancy word for this too (sorry): truncation . Line 4? Error: As humans, we can easily figure out what is supposed to happen. Sadly, computers are unable to make that leap. IMPORTANT: A key point to know is that the value being converted by the parseInt function must "resemble" a number in order for parseInt() to be able to figure out the conversion.

  12. Solving our earlier problem using parseInt() txtAge var age = document.getElementById('txtAge').value; //age is holding "35" (i.e. a string) age = parseInt(age); var nextYear = age+1; alert("Next year you will be " + nextYear); How does it work? 1. We retrieve the value entered into the form, and store it in the variable age. Note that age is holding a string. (Recall that all data that comes from an HTML form comes in as a string). 2. The parseInt()function will look at the string 35 and do its very best to convert that string to an integer. In this case, it will have no problem doing so. 3. We then take our integer 35 that was generated by the parseInt() function, and assign it to the variable age. So whereas age was previously holding the string 35 , we have now reassigned age to hold the integer 35. 4. Because age is holding an integer, the formula age+1now has an integer on both sides of the +operator. Therefore, the + operator will do addition. 12

  13. age = parseInt(age) Explained var age = document.getElementById('txtAge').value; //let's say the user entered 35 in the txtAge text field //this means that 'age' is holding the string "35" "35" age age = parseInt(age); // parseInt("35") will produce the integer 35. // We then assign that 35 to the variable 'age' // So 'age' is now holding the integer 35 35 age Important: Note that when you assign a value to a variable, any previous value that was stored inside will be deleted and replaced by the new value. In this example, the previous value of "35" will be replaced by the new value: 35. var nextYear = age+1; alert("Next year you will be " + nextYear); 36 nextYear 13

  14. How the parseInt()function works Every built-in function comes with a little "instruction book" that programmers typically refer to as the "documentation" or "docs". Programmers who encounter a useful function typically spend some time checking out the documentation to get an idea of how the function works and any potential pitfalls or 'gotchas' that they might need to know about. Here are a few points taken from the parseInt() documentation: The function will examine the "argument" (the information inside the parentheses). If the argument does NOT begin with a digit or a minus sign, the function will return an error. If the argument begins with a digit or a minus sign, the function will examine the characters in the argument until it encounters any non-digit character. The function will then return all the numeric characters it encountered. It will return the as an integer. (Not as a string). As is very often the case, one of the best ways to see how a function works is to look at some examples: 1. parseInt("359") returns the integer 359 2. parseInt("(352)"); returns an error does not start with a or digit 3. parseInt("35.9"); returns the integer 35 4. parseInt("-35.9"); returns the integer -35 5. parseInt("35.3.4.5"); returns the integer 35 6. parseInt("I am 35 years old."); Error does not begin with a digit or 14

  15. Summary - Key Points Whenever you read in a value from a form and wish that value to be treated as an integer number, you should invoke the parseInt()function. txtYearBorn Example: var birthYear = document.getElementById('txtYearBorn').value; //Clearly we wish 'birthYear' to hold an integer //Therefore, we must do the following: birthYear = parseInt(birthYear); //birthYear can now be treated as a regular number From this point forward, i.e. throughout the remainder of the course: 1. Whenever you read in a value from a web form that you know is intended to be an integer quantity, you must invoke the parseInt() function on that number. 2. However, if you are NOT reading in a quantity, (e.g. you are retrieving, say, a telephone number, or a zip code, or a name, etc), you should never invoke the parseInt() function. The grader will deduct points every time you forget to do so! 15

  16. parseFloat() What if the number you are planning to retrieve may contain decimals? E.g. The time to complete a 100 meter dash, the cost of a gallon of gas, etc Recall that parseInt()stops parsing the instant it encounters any non numeric character such as a decimal. Therefore, if you want to keep your decimals, you would not want to use parseInt(). Instead, you must use parseFloat() For example, suppose you are recording the race time for a 100 meter sprint where the times are often recorded to hundredths of a second. In this case, we would absolutely need to keep the decimal places. Therefore, we must use parseFloat() instead of parseInt() var raceTime = document.getElementById('txtRaceTime').value; raceTime = parseFloat(raceTime); txtRaceTime 16

  17. Should I use parseInt() or parseFloat() ? What if you are not sure if the value will have decimals or not? In this situation, the best bet will be to err on the side of caution and use parseFloat(). That way, if the user does enter a value with decimals, you won t lose those decimal values. Even if the user ends up entering an integer value, all that will happen is that you will see a '.0' appended to the end of the value. o For example, if the user enters exactly 14 for, say, a race time, then parseFloat() will convert it to 14.0. Key Point: If you're not sure, choose parseFloat() 17

  18. When NOT to use parseInt() and parseFloat() From this point forward, you must always use parseInt() or parseFloat() But ONLY when retrieving information that involves a quantity! Examples: age, weight, cost of an item, time to run a race, number of days to ship a package, etc, etc, etc If you are not reading in a quantity (e.g. a telephone number, zip code, name, etc), do not use a parse function! In the same way that you will be penalized for failing to use these functions when appropriate, you will also be penalized if you use them in inappropriate situations. One good rule of thumb is to ask yourself if there is any conceivable situation in which you might want to do a mathematical calculation with the number. e.g. If you are asking someone their birth year, you might want to subtract it from the current year in order to determine how old they are. So you would want to parse it. As long as you review and understand the underlying concept, and you should have no problem at all, figuring out when to and when not-to use these functions. 18

  19. Examples Which of the following should be parsed? Should we use parseInt or parseFloat? Or neither? 1. The user s age 2. The user s phone number 3. The user s birth year 4. The user s weight 5. The user s zip code Answers: 1. parseFloat() most likely. While most users will enter a whole number, you never know if someone might enter a decimal. Remember: If you think there is even a possibility that the user would enter a value with a decimal, then you should use parseFloat(). 2. Neither. Do not use any parse function. Even if the user enters the number without any parentheses, or dashes, etc, it is still a string. It is hard to envision a situation where you would ever do math on it! 3. parseInt(). You might want to subtract from the current year in order to determine their age. 4. Probably parseFloat(). There are definitely people who know their weight to the nearest 10thof a pound! Because this is a real possibility, I d use parseFloat() here. It won t hurt anything if they do enter a whole number. 5. Do not use a parse function here. Other than sorting (which you can do with strings), there is no math I can envision being done on a zip code! 19

  20. File: parse_example.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Parse Example</title> </head> <body> <h1>Parse Example</h1> <p>How old are you now? <input type="text" id="txtAge"> <p><button onclick="calcNextYear()">How old will I be next year?</button> <script> function calcNextYear() { var ageThisYear, ageNextYear; ageThisYear = document.getElementById("txtAge").value; ageThisYear = parseInt(ageThisYear); ageNextYear = ageThisYear + 1; alert("Next year, you will be: " + ageNextYear + " years old!"); } </script> </body> </html> Reminder: We are only using alert() functions in these examples to minimize unrelated code. In the real world, we would use innerHTML. 20

  21. Be sure to invest the necessary time being able to apply as well as understanding with the techniques we have just discussed. You will encounter parseInt() and parseInt() constantly over the remainder of the course as well as in your exams. 21

  22. <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Temperature Converter</title> </head> <body> <h1>Temperature Converter</h1> <form id="conversionForm"> <p>Enter a temperature in fahrenheit: <input type="text" id="txtFahrenheit"> <button type="button" onclick="convertToCelcius()">Convert</button> <! We *need* the type attribute above! Otherwise our innerHTML won't work. --> </form> File: fahrenheit_celcius_converter.html IMPORTANT: One of the best ways to finesse your programming skills and learn new ones is by studying existing code. We will experiment with this approach here by introducing a couple of new points without several slides of formal PowerPoint discussion. However, I will provide some explanation. There are some important concepts discussed in this example be sure to study it closely, and review periodically! For reasons beyond the scope of this discussion, the innerHTML command won t work unless we include the type="button" attribute. So, if ANY button is invoking a function that includes innerHTML, be sure to include this attribute. <div id="results"> </div><!-- end of results div --> <script> function convertToCelcius() { var fahrenheit, celcius; var resultsString; To be on the safe side, feel free to include this attribute in all of your buttons if you like. (I ve also included this on the assignment checklist). Remember to close <div> sections with a comment indicating the name of the section that was closed. fahrenheit = document.getElementById('txtFahrenheit').value; fahrenheit = parseFloat(fahrenheit); //people may well enter a decimal here, so use parseFloat Remember that we should NOT parse items that do not require it! In this case, the variable celcius is ALREADY holding a number. It is not a string, so we do not need to parse it! celcius = (fahrenheit-32)*5/9; //Should we parse 'celcius' ?? //No! celcius is holding a number -- NOT a string //therefore we do not need to parse it. celcius = celcius.toFixed(2); //limit to 2 decimal places The toFixed() function is quite useful! Note that we must reassign the value returned by this function to the same variable. resultsString = fahrenheit + "&#176;F corresponds to " + celcius + "&#176;C."; //Note the entity code! We create a string variable to hold our rather long concatenated string. We can then assign that string to our innerHTML command. document.getElementById("results").innerHTML = resultsString; } </script> </body> </html> When dealing with a very long string, this technique makes the code easier to write and follow. 22

  23. Note that there is a JavaScript function called Number()(yes, the 'N' is capitalized). This function works very similarly to the parse functions we have been discussing. FYI There are good reasons both for and against using Number() instead of the parse functions. The parse functions require a bit more effort to understand and work with up front, but they are very useful for us to explore datatypes. And understanding datatypes is super-important in programming. Number() Once you understand the parse functions, should you choose or work with a team that uses Number() down the road, you will have very little difficulty learning how to use that function. 23

  24. FILE: simple_conversions.html This file is intended to be an exercise in self-learning. Click on the file to open in your browser, then copy/paste the code into your editor so that you can study and, more importantly, experiment with it. Study this code. In particular, note: The use of multiple functions on the page. This is fine - and in fact, very common! Having different buttons - each of which invokes its own function. Extracting a specific part of the date from JavaScript's Date() function.

More Related Content