Working with Data


The data in your JavaScript programs can be of many different types. For example, you might have some textcalled a text string that you want to display, like this:

 document.write("Hello, welcome to my Web page!") 

Or you might be writing a compound interest calculator for users and need to keep in mind the interest rate, the amount the user has invested, and the length of time the user wants to collect interest for to be able to calculate what he wants to know. Or you might even have a database of items to sell and need to search that database for matches to what the user is looking for. To make your programs actually do something, you won't get very far without being able to handle some data and work on it.

Internally, JavaScript has several data types it uses. For example, the string data type lets JavaScript handle strings of text, the number data type lets JavaScript handle numeric values, and so on. Here are the different data types that JavaScript supports internally:

  • String. A string of text, such as "Welcome to my web page!" or "I think that's an error."

  • Number. These are numeric values, such as integers like 1, 1, 0, and 5014, or floating-point values such as 1.000, 3.1415, and 0.07.

  • Boolean. Boolean values are "truth" values, and can hold only two values: true or false. These will be more important when we start testing our datafor example, checking whether a temperature is greater than 72 will give us a value of true or false.

  • Null. Null values indicate a null result in JavaScript. If you try to access data past the end of a data list, for example, you may get a null value. The idea here is that there's nothing to report.

  • Object. We've already seen a great deal about the objects built in to browsers and built in to JavaScript itself. Instead of simple data such as strings or numbers , these objects are handled using the object data type internally. Later on in this book, we'll see how to create our own custom objects.

  • Function. Even function definitions, which we'll see in the next chapter, can be treated as data in JavaScript.

You can use data of these various types in two ways in your code. First, you can embed it directly in JavaScript statements, like this:

 document.write("Hello")  document.write(3.1415926) 

These directly embedded data items are called literals , they're values that appear in your code statements. Here, I'm writing the string "Hello" and the number 3.1415926 to a web page and storing those values as literals in the code.

The second way to store data is to use variables , and I'll take a look at working with variables now.



Inside Javascript
Inside JavaScript
ISBN: 0735712859
EAN: 2147483647
Year: 2005
Pages: 492
Authors: Steve Holzner

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net