Home

JavaScript Operations on Variables

 

JavaScript Variables

 

Introduction

A variable is an amount of memory space reserved to store a piece of information of your code. To use such a memory space, you must first let the browser know that you would need it. For the browser to reserve such a memory space for you, and to use it eventually, you must give it a name. The memory space that is reserved will be used to receive some values from your application and to make such values available when your code needs them. The content of this reserved memory space can change or vary regularly. For example, if you create a web page that acts as an employment application and include a text box for the first name, the content of the first name text box will be different depending on each visitor. The memory space that stores the first name of the visitors will vary from one visitor to another visitor. For this reason, it is called a variable.

 

The Name of a Variable

The primary piece of information you must specify about a variable is its name and there are rules you must follow.

The name of the variable:

  • Must start with a letter or an underscore character
  • After the first character, can contain letters, digits, and underscores
  • Cannot contain space

When naming your objects, you should be a little explicit. A name such as d intended to designate a date hired is difficult to figure out. On the other hand, if you plan to use a variable that represents a customerís address, you can just call the variable address. If the name is a combination of words, such as firstname, you start the first letter of the first part in lowercase and the first character of the other parts in uppercase. For example, instead of studentname, you can use studentName; instead of dateofbirth, use dateOfBirth. Various programmers use different naming conventions. For example, some programmers use the underscore to append two names of a variable. You are free to adopt which ever convention suits you.

To use a variable in your script, you can just type it. Here is an example:

<SCRIPT LANGUAGE="JavaScript">
  NumberOfStudents
</SCRIPT>

With such a variable, you can perform any of the operations we will learn shortly.

Once the variable has been used somewhere, the browser reserves a space in memory for it. If you use another or new name for a variable in the same script, if the new variable has a different name than a former variable, the browser would reserve a new space in memory for it. You can continue introducing variables like that as your script needs them.

Be careful not to mistakenly type the name of variable that you want to reuse in your program. For example, if you have a variable named numberOfStudents in your script, then find out that you want to use it in an operation, if you type nbrOfStudents instead of numberOfStudents, since both names are different, a new memory space would be reserved for nbrOfStudents because the browser would consider that nbrOfStudents is a new variable. Trying to use both variables as one would lead to unpredictable results. To avoid this confusion, an alternative is to first tell the browser that you have a variable you want to use. By doing this, the browser would be a "witness" that a certain variable exists. This is not a bulletproof solution but can help to improve your code.

Letting the interpreter know about a variable is referred to as declaring the variable. To declare a variable, use the var keyword, followed by a name for the variable, followed by a semi-colon. Here are examples of declaring variables:

<Script Language="JavaScript">
  var firstName;
  var hiredDate;
  var hourlySalary;
</Script>

Although the var keyword is used to declare a variable, it can be used for any kind of variable. It can be used to declare a variable that is used for a natural number (integer), a decimal number (floating-point or double-precision number), or a string.

If you need to use many variables, you can declare more than one on the same line. To do this, separate them with a comma. Here is an example:

<Script Language="JavaScript">
  var FullName, EmailAddress;
  var Address, City, State, ZIPCode;
</Script>
 

JavaScript and Operations

 

Introduction

One of the most common assignments you will hand to your scripts consists of performing operations. JavaScript is equipped with various kinds of operators to respond to virtually any type of operation you need.

The Assignment =

We saw that, when declaring a variable, a memory space is reserved for it. Such a space is empty until you fill it with a value. This is performed with the assignment operation. The assignment operation gives a value to a variable. It is performed using the = operator. Its syntax is:

VariableName = Value

The VariableName factor must be a valid variable name. It cannot be a value such as a numeric value or a (double-quoted) string. Here is an example that assigns a numeric value to a variable:

<Script Language="JavaScript">
  salary = 12.55;
</Script>

Once a variable has been declared and assigned a value, you can call the document.write() method to display its value. Since the variable is part of your script and not an HTML tag, it doesn't need to be included in double-quotes (the proper sentence is that, "it doesn't need to be passed as a string"; but we have not learned what it means to pass an argument). Here is an example:

<Script Language="JavaScript">
  Salary = 12.55;
  document.write(Salary);
</Script>

To improve, safeguard, and make your code more efficient, we have learned that you should declare a variable before using it. This is done using the var keyword. The above script could be written as follows:

<Script Language="JavaScript">
  var Salary;
  Salary = 12.55;
  document.write(Salary);
</Script>

The above code declares a variable before assigning it a value. You will usually perform this assignment when you want to change the value held by a variable. The first time the browser encounters a variable, you can make sure that the variable is holding a value, just as done above. Alternatively, you can assign a value to a variable when you are declaring it, on the same line as its declaration. The above script can be changed as follows:

<Script Language="JavaScript">
  var Salary = 12.55;
  document.write(Salary);
</Script>

Providing a starting value to a variable when it is declared is referred to as initializing the variable.

Practical Learning: Using the Assignment Operator

  1. Start your text editor
  2. In the empty file, type the following:
     
    <Script Language="JavaScript">
      var EarningsJob1, EarningsJob2;
      
      EarningsJob1 = 325.38;
      EarningsJob2 = 580.64;
      
      document.write("<p>Salaries</p>");
      document.write("Job 1: $");
      document.write(EarningsJob1);
      document.write("<br>");
      document.write("Job 2: $");
      document.write(EarningsJob2);
    </Script>
  3. Save the file as operators.htm in the JavaScript Lessons folder
  4. Preview the file in the browser and return to your text editor

The Addition +

The addition is an operation used to add one value to another. The syntax used it:

Value1 + Value2

To perform this operation, the interpreter would add the value of Value1 to that of Value2. You can use such an operation to display the result on an HTML page. Here is an example:

<SCRIPT LANGUAGE="JavaScript">
  document.write( 125 + 48);
</SCRIPT>

The addition operation as implemented in JavaScript can be applied to natural numbers called integers, to floating-point numbers called float or double-precision numbers, or to strings. Here is an example that illustrates this:

<SCRIPT LANGUAGE="JavaScript">
  // The addition operation applied
  // to two natural numbers: integers
  document.write( 125 + 48);
  document.write("<br>");
  // to decimal numbers: float or double
  document.write(2540.25 + 662.38);
  document.write("<br>");
  // to two strings
  document.write("Roland " + "Stewart");
</SCRIPT>

You can also apply this operation on variables. For example, once a variable holds a value, you can add another value to it:

Salary + 0.55

You can also add the values of two variables using their names:

SalaryWeek1 + SalaryWeek2

As done in the above script, you can display the addition using the document.write() method.

After the addition operation is performed, it produces a resulting value. Sometimes you will not simply need to display the value on a web page: you may want to use it in another calculation. Therefore, you can store the result in a another variable, then use the result as you see fit.

Practical Learning: Performing Additions

  1. To continue with the HTML file, change it as follows:
     
    <Script Language="JavaScript">
      var EarningsJob1, EarningsJob2;
      var TotalForTheWeek;
    
      EarningsJob1 = 325.38;
      EarningsJob2 = 580.64;
      TotalForTheWeek = EarningsJob1 + EarningsJob2;
    
      document.write("<p>Salaries</p>");
      document.write("Job 1: $");
      document.write(EarningsJob1);
      document.write("<br>");
      document.write("Job 2: $");
      document.write(EarningsJob2);
    
      // Although IE can interpret the following line, most other browsers can't
      document.write("<hr align=left width=120 color=#FF5758>");
      document.write("Total: $" + TotalForTheWeek);
    </Script>
  2. Save the file and preview it in the browser
     
  3. After previewing the page, return to your text editor and close

The Subtraction -

The subtraction is an operation used to subtract one value from another. The syntax used it:

Value1 - Value2

To perform this operation, the interpreter would subtract the value of Value1 from that of Value2. You can use such an operation to display the result on an HTML page. Here is an example:

<SCRIPT LANGUAGE="JavaScript">
  document.write(208.55 - 42.16)
</SCRIPT>

The subtraction operation as implemented in JavaScript can be applied to natural numbers or decimal numbers. The subtraction can also be applied on variables and/or their values.

The Multiplication *

The multiplication is used to add a number to itself a certain number of times. This operation is performed using the * operator. Its syntax is:

Value1 * Value2

This operation can be performed on numeric values as follows:

<Script Language="JavaScript">
  document.write(15.55 * 240.25)
</Script>

The multiplication operation can be applied to values or variables that hold valid values. After the operation is performed, it produces a result that can be displayed on a web page or stored in a variable for later retrieval.
  

The Division /

The division operation is used to divide a numeric value or the value held by a variable. The division operation is performed using the forward slash. Its syntax is:

Value1 / Value2

This operation can be performed on numeric values as follows:

<Script Language="JavaScript">
  document.write("Daily Earnings: ")
  document.write(425.65 / 7)
</Script>

The division operation can be applied to values or variables that hold valid values

The Negation -

In mathematics, a number written as 10500 or 44.12 is considered a positive number. In the computer world, we referred to such a number as unsigned (because it doesn't have a sign). An unsigned number has a value greater than 0. If a number is less than 0, such a number qualifies as negative. To indicate that a number is negative, you write the - sign on its left. For example -32 is called a negative number.

A value or a variable is made negative by applying the - operator to its left. Here is an example:
 

<Script Language="JavaScript">
  var Temperature
  Temperature = -32
</Script>

The negation operator is referred to as a unary operator because it applies to only one value or variable. As illustrated above, a negative number can be assigned to a variable. A variable can also be made negative by using this operator.

 

Previous Copyright © 2002-2009 FunctionX, Inc. Next