JavaScript Editor JavaScript Debugger     JavaScript Editor 



Team LiB
Previous Section Next Section

Chapter 3: Data Types and Variables

Although JavaScript was primarily intended to be used to manipulate text in the form of HTML Web pages within a browser, the data types it offers go well beyond what would be required for the task. Present in JavaScript are most—if not all—of the data types you’d find in other modern scripting languages, as well as a robust set of features with which to manipulate them.

The basic types JavaScript supports are numbers, strings, and Booleans. More complex types such as objects, arrays, and functions are also part of the language. This chapter covers in detail the basic data types and their usage. Functions and composite types, such as objects, are also briefly introduced, but a complete exposition of their capabilities is reserved for Chapters 5 and 6.

Key Concepts

A variable can be thought of as a container that holds data. It’s called a “variable” because the data it contains—its value—varies depending on your script. For example, you might place the total price of items a customer is buying in a variable, and then add tax to this amount, storing the result back in the variable. The type of a variable describes the nature of the data stored. For example, the type of a variable holding the value 3.14 would be number while the type of a variable holding a sentence would be string. Note that “string” is programming language lingo for a sequence of characters—in other words, some text.

Since you need to have some way to refer to variables, each variable is given an identifier, a name that refers to the container and allows the script to access and manipulate the data it contains. Not surprisingly, a variable’s identifier is often referred to as its name. When scripts are run, the JavaScript interpreter (the facility within the browser that executes JavaScript) needs to allocate space in memory to store a variable’s value. Declaring a variable is the process of telling the interpreter to get ready to store data in a new variable. In JavaScript, variables are declared using the var keyword with the name of the variable you wish to declare. For example, you might write

var firstName;

You can now store data in the variable known by the identifier firstName. Presumably, you’d be storing a string here. We could then assign a value like "Thomas" to the variable. We call the string "Thomas" a literal, which describes any data appearing directly in the source code. The complete example is now

var firstName;
firstName = "Thomas";

The illustration here demonstrates all the terms used so far together.

Although it is good programming practice to declare variables before use, JavaScript allows the implicit declaration of variables by using them on the left-hand side of an assignment. That is, when the interpreter sees that a script would likely stick data into a variable that hasn’t been declared, it automatically allocates space for the variable without the programmer having to use the var keyword. For example, you might just assign a variable, like so:

lastName = "Schneider";

Many programmers use this type of implicit declaration to save time when coding. It’s faster and easier to not bother declaring variables before using them. Unfortunately, it’s also not a good idea. Scripts written without variable declarations are significantly harder to read than those that use explicit declarations. Implicit declaration can also lead to subtle, hard-to-find errors involving variable scope, a topic we’ll discuss later in the chapter. Unless you’re writing a very simple script (less than a dozen lines), always explicitly declare your variables.

Инструменты для раскрутки сайтов
Сейчас интернет стал замечательным источником прибыли как для создателей сайтов так и для бизнесменов. Многие создают или заказывают сайты чтобы заработать в интернете. Если у вашего сайта хороший дизайн и он наполнен полезной информацией для людей, он может быть практически незаметен поисковыми роботами и как следствие иметь низкий трафик. Для того чтобы изменить эту ситуацию вам необходимо воспользоваться поисковой оптимизацией.

Weak Typing

Most high-level languages, including C and Java, are strongly typed. That is, a variable must be declared before it is used, and its type must be included in its declaration. Once a variable is declared, its type cannot change. At the other end of the spectrum are untyped languages such as LISP. LISP supports only two primitive data types: atoms and lists. It does not draw any distinction between strings, integers, functions, and other data types. As a weakly typed language, JavaScript falls somewhere in between these two extremes. Every variable and literal has a type, but data types are not explicitly declared. For example, we might define a variable favNumber to hold our favorite number and set it to a value of 3. Then we might reassign the variable to be the string value "San Diego".

var favNumber;
favNumber = 3;
favNumber = "San Diego";

While logically the example doesn’t make much sense, it clearly indicates how weak typing in JavaScript works. First, when the variable favNumber is declared, it is empty. In fact, its data type is actually the type undefined. Then we assign it to the number 3, so its data type is 3. Next we reassign it to the string "San Diego", so the variable’s type is now string. As you can see, types are inferred from content, and a variable automatically takes on the type of the data it contains. Contrast this to a more strongly typed language like C, Java, or Pascal. In doing so you might define the type allowed in favNumber explicitly, like so:

var favNumber : number;

Given this example, an assignment like

favNumber = 3;

would be perfectly valid. But if you assigned some non-numeric type to the variable like

favNumber = "San Diego";

it would cause an error or warning to occur. It should start to become clear that weak typing provides some simplicity since programmers don’t have to worry about types, but it does so at the expense of runtime errors and security issues. We’ll see many issues with weak typing throughout both the chapter and the book. For now, the concept is enough. Let’s begin to look at each of the types in turn.


Team LiB
Previous Section Next Section


JavaScript Editor JavaScript Debugger     JavaScript Editor


©