Home > Articles > Open Source > Ajax & JavaScript

This chapter is from the book

This chapter is from the book

3.2 Variables

Variables are fundamental to all programming languages. They are data items that represent a memory storage location in the computer. Variables are containers that hold data such as numbers and strings. Variables have a name, a type, and a value.

num = 5;           // name is "num", value is 5, type is numeric
   friend = "Peter";  // name is "friend", value is "Peter", type is string
   

The values assigned to variables may change throughout the run of a program whereas constants, also called literals, remain fixed. (JavaScript 1.5 introduced constants and since they are so new, they are only recognized by Netscape 6.)

JavaScript variables can be assigned three types of data:

  • numeric

  • string

  • Boolean

Computer programming languages like C++ and Java require that you specify the type of data you are going to store in a variable when you declare it. For example, if you are going to assign an integer to a variable, you would have to say something like:

int n = 5;

And if you were assigning a floating-point number:

float x = 44.5;

Languages that require that you specify a data type are called "strongly typed" languages. JavaScript, conversely, is a dynamically or loosely typed language, meaning that you do not have to specify the data type of a variable. In fact, doing so will produce an error. With JavaScript, you would simply say:

n = 5;
x = 44.5;

and JavaScript will figure out what type of data is being stored in n and x.

3.2.1 Valid Names

Variable names consist of any number of letters (an underscore counts as a letter) and digits. The first letter must be a letter or an underscore. Since JavaScript keywords do not contain underscores, using an underscore in a variable name can ensure that you are not inadvertently using a reserved keyword. Variable names are case sensitive; e.g., Name, name, and NAme are all different variable names. Refer to Table 3.2.

Table 3.2. Valid and invalid variable names.

Valid Variable Names

Invalid Variable Names

name1

10names

price_tag

box.front

_abc

name#last

Abc_22

A-23

A23

5

3.2.2 Declaring and Initializing Variables

Variables must be declared before they can be used. To make sure that variables are declared first, you can declare them in the head of the HTML document. There are two ways to declare a variable: either explicitly preceded by the keyword var, or not. Although laziness may get the best of you, it is a better practice to always use the var keyword.

You can assign a value to the variable (or initialize a variable) when you declare it, but it is not mandatory, unless you omit the var keyword. If a variable is declared but not initialized, it is "undefined."

FORMAT

var variable_name = value;   // initialized
   var variable_name;           // unitialized
   variable_name;               // wrong
   

To declare a variable called firstname, you could say

var first_name="Ellie"
   

or

first_name ="Ellie";

or

var first_name;

You can declare multiple variables on the same line by separating each declaration with a comma. For example, you could say

var first_name, var middle_name, var last_name;
   

Example 3.5

    <html>
    <head>
    <title>Using the var Keyword</title>
        <script language="JavaScript">
1          var language="English";    // Variable is initialized
   2          var name;    // OK, undefined variable
   3          age;      //  Not OK!  var keyword missing  ERROR!
   4          document.write("Name is "+ name);
   </script>
   </head>
   <body></body>
   </html>
   

EXPLANATION

  1. The variable called language is defined and initialized. The var keyword is not required here, but is recommended.

  2. Because the variable called name is not initialized, the var keyword is required here.

  3. The variable called age is not assigned an initial value. The var keyword is required. Without it, the program produces errors, shown in the output for Netscape and Explorer, in Figures 3.4 and 3.5, respectively.

    03fig04.jpgFigure 3.4. Netscape error (JavaScript Console).

    03fig05.jpgFigure 3.5. Internet Explorer error.

  4. This line will not be printed until the variable called age is defined properly. Just use the var keyword as good practice, even if it isn't always required!

3.2.3 Dynamically or Loosely Typed Language

Remember, strongly typed languages like C++ and Java require that you specify the type of data you are going to store in a variable when you declare it, but JavaScript is loosely typed. It doesn't expect or allow you to specify the data type when declaring a variable. You can assign a string to a variable and later assign a numeric value. JavaScript doesn't care and at runtime, the JavaScript interpreter will convert the data to the correct type. Consider the following variable, initialized to the floating-point value of 5.5. In each successive statement, JavaScript will convert the type to the proper data type; see Table 3.3.

Table 3.3. How JavaScript converts datatypes.

Variable Assignment

Conversion

var item = 5.5;

Assigned a float

item = 44;

Converted to integer

item = "Today was bummer";

Converted to string

item = true;

Converted to Boolean

item = null;

Converted to the null value

Example 3.6

    <html>
1       <head>
   <title>JavaScript Variables</title>
   2       <script language="JavaScript">
   3          var first_name="Christian"; // first_name is assigned a value
   4          var last_name="Dobbins";    // last_name is assigned a value
   5          var age = 8;
   6          var ssn;     // Unassigned variable
   7          var job_title=null;
   </script>
   8       </head>
   9       <body bgcolor="lightblue">
   <font="+1">
   10         <script language="JavaScript">
   11            document.write("<b>Name:</b> " + first_name + " "
   + last_name + "<br>");
   12            document.write("<b>Age:</b> " + age + "<br>");
   13            document.write("<b>Ssn:</b> " + ssn + "<br>");
   14            document.write("<b>Job Title:</b> " + job_title + "<br>");
   15            ssn="xxx-xx-xxxx";
   16            document.write("<b>Now Ssn is:</b> " + ssn , "<br>");
   </script>
   17      <body><p><img src="Christian.gif"></body>
   </html>
   

Output:

11  Name: Christian Dobbins
   12  Age: 8
   13  Ssn: undefined
   14  Job Title: null
   16  Now Ssn is: xxx-xx-xxx
   

EXPLANATION

  1. This JavaScript program is placed within the document head. Since the head of the document is processed before the body, this assures you that the variable definitions will be defined first.

  2. This is where the first JavaScript program begins.

  3. The string "Christian" is assigned to the variable called first_name.

  4. The string "Dobbins" is assigned to the variable called last_name.

  5. The number 8 is assigned to the variable called age.

  6. The variable called ssn is not assigned any value at all. It is an uninitialized variable. The return value is undefined.

  7. The value null is assigned to the variable called job_title. Null is used to set a variable to an initial value different from other valid types, but if used in an expression the value of null will be converted to the appropriate type.

  8. The document head ends here.

  9. The body of the document starts here.

  10. A new JavaScript program starts here. All the variables declared in the head of the document are available here. Variables that are available throughout the entire document are called global variables.

  11. The document.write() method concatenates the values of the strings with the + sign and sends them to the browser to display on the screen.

  12. The value of the variable called age is displayed.

  13. The variable called ssn was declared, but not initialized. It has no value, which JavaScript calls undefined.

  14. The variable job_title was assigned null, a place-holder value. The null string is returned.

  15. The variable ssn is assigned a string value. It is no longer undefined. Even though the variable was declared in the head of the document, as long as it was declared, it can be assigned a value anywhere else in the document.

  16. The value of the variable ssn is displayed. Figure 3.6 shows the output in Internet Explorer.

    03fig06.jpgFigure 3.6. Output from Example .

3.2.4 Scope of Variables

Scope describes where a variable is visible, or where it can be used, within the program. JavaScript variables are either of global or local scope. A global variable can be accessed from any JavaScript script on a page, as shown in Example 3.6. The variables we have created so far are global in scope.

It is often desirable to create variables that are private to a certain section of the program, thus avoiding naming conflicts and accidentally changing a value in some other part of the program. Private variables are called local variables. Local variables are created when a variable is declared within a function. Local variables must be declared with the keyword, var. They are accessible only from within the function from the time of declaration to the end of the enclosing block, and they take precedence over any global variable with the same name. (See Chapter 7, "Functions.")

3.2.5 Concatenation and Variables

To concatenate variables and strings together on the same line, the + sign is used. The + sign is an operator because it operates on the expression on either side of it (each called an operand). Sometimes the + sign is a string operator and sometimes it is a numeric operator when used for addition. Addition is performed when both of the operands are numbers. In expressions involving numeric and string values with the + operator, JavaScript converts numeric values to strings. For example, consider these statements:

var temp  = "The temperature is  " + 87;
 // returns "The temperature is 87"
   var message =  25  + "  days till Christmas";
   // returns "25 days till Christmas"
   

But, if both operands are numbers, then addition is performed:

var sum = 10 + 5;  // sum is 15
   

Example 3.7

    <html>
    <head><title>Concatenation</title></head>
        <body>
            <script language="JavaScript">
   1              var x = 25;
   2              var y = 5 + "10 years";
   3              document.write( x + " cats" , "<br>");
   4              document.write( "almost " + 25 , "<br>");
   5              document.write( x + 4, "<br>");
   6              document.write( y, "<br>");
   7              document.write(x  +  5 + " dogs" , "<br>");
   8              document.write(" dogs"  + x + 5 , "<br>");
   
   </script>
   </body>
   </html>
   

Output:

3   25 cats
   4   almost 25
   5   29
   6   510 years
   7   30 dogs
   8   dogs255
   

EXPLANATION

  1. Variable x is assigned a number.

  2. Variable y is assigned the string 510 years. If the + operator is used, it could mean the concatenation of two strings or addition of two numbers. JavaScript looks at both of the operands. If one is a string and one is a number, the number is converted to a string and the two strings are joined together as one string, in this example, the resulting string is 510 years. If one operand were 5 and the other 10, addition would be performed, resulting in 15.

  3. A number is concatenated with a string. The number 25 is converted to a string and concatenated to " cats", resulting in 25 cats.

  4. This time, a string is concatenated with a number, resulting in the string almost 25.

  5. When the operands on either side of the + sign are numbers, addition is performed.

  6. The value of y, a string, is displayed.

  7. The + operators works from left to right. Since x and y are both numbers, addition is performed, 25 + 5. 30 is concatenated with the string " dogs".

  8. Since the + works from left to right, this time the first operand is a string being concatenated to a number, the number is converted to string dogs25 and concatenated with string 5.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020