Understanding JavaScript Data Types

JavaScript uses data types to determine how to handle data that is assigned to a variable. The variable type determines what operations you can perform on the variable, such as looping or executing. The following list describes the types of variables that you will most commonly work with in this book:

Image String: This data type stores character data as a string. The character data is specified by either single or double quotes. All the data contained in the quotes will be assigned to the string variable. For example:

var myString = 'Some Text';
var anotherString = 'Some More Text';

Image Number: This data type stores the data as a numerical value. Numbers are useful in counting, calculations, and comparisons. Some examples are:

var myInteger = 1;
var cost = 1.33;

Image Boolean: This data type stores a single bit that is either true or false. Booleans are often used for flags. For example, you might set a variable to false at the beginning of some code and then check it on completion so see if the code execution hit a certain spot. The following examples define true and false variables:

var yes = true;
var no = false;

Image Array: An indexed array is a series of separate distinct data items, all stored under a single variable name. Items in the array can be accessed by their zero-based index, using array[index]. The following is an example of creating a simple array and then accessing the first element, which is at index 0:

var arr = ["one", "two", "three"];
var first = arr[0];

Image Object Literal: JavaScript supports the ability to create and use object literals. When you use an object literal, you can access values and functions in the object by using object.property syntax. The following example shows how to create and access properties of an object literal:

var obj = {"name": "Brad", "occupation": "Hacker", "age": "Unknown"};
var name = obj.name;

Image Null: Sometimes you do not have a value to store in a variable either because it hasn’t been created or you are no longer using it. At such a time you can set a variable to null. Using null is better than assigning a value of 0 or an empty string ("") because those may be valid values for the variable. By assigning null to a variable, you can assign no value and check against null inside your code, like this:

var newVar = null;


Note

JavaScript is a typeless language. You do not need to specify in the script what data type a variable is. The interpreter automatically figures out the correct data type for a variable. In addition, you can assign a variable of one type to a value of a different type. For example, the following code defines a string variable and then assigns it to an integer value type:

var id="testID";
id= 1;


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.235.225