Virtual Open Schooling Online courses available at Virtual Open Schooling (VOS), for more details kindly click here!
NIOS Silver Jubilee Year
NIOS

Variables in Java Script

From NIOS
Jump to: navigation, search
Previous Page Home Page Next Page
ICT Applications

Variables, data types, expressions and operators form the core of any programming language and JavaScript is no exception to this.

Define Variable

Variables are storage containers to store data of varioustypes like “computer”, 65000, and 2765.50. Like any otherprogramming language, JavaScript allows user to declarevariables and use the values stored in them.

Variable names in JavaScript can begin with an uppercaseletter (A–Z), lowercase (a–z), or underscore (_) character. Therest of characters may be letters, the underscore character,or digits (0–9). JavaScript is case sensitive, the variableresult not same as ‘RESULT’.

Variable Data Types

In JavaScript, variables can store following data types:

Data types Examples
Number Store numeric value(for example: 3, 3.5)
String Store alphanumeric characters(for example: "computer", "555-123")
Boolean Store true or false values only

Declaring Variables

In JavaScript, you can declare a variable using the var keyword,as shown in below:

  • var itemName;* var itemPrice;You can also assign a value to the variable at the time ofdeclaration. For example: var itemName="computer", varitemPrice="35000"

Arrays

Arrays are used to store a sequence of values of same data type.These values are stored in the indexed location within the array.For Example: If you want to store three items of the same type,you can create an array with the name of the items and store theirvalues in the same. The following statement declares an array of length 3: itemNames=new Array(3) Three item Names can be stored by using the followingstatements:

  • itemNames[0]="Computer"
  • itemNames[1]="TV"
  • itemNames[2]="Radio"

The same can also be declared as follows:
itemNames= new Array("Computer","TV","Radio")
To access the names stored in the array, you can use the following statements:
document.write(itemNames[0])
document.write(itemNames[1])
document.write(itemNames[2])
Below example shows use of arrays.
<HTML>
<HEAD>
<TITLE>JavaScript Example of Use of Arrays </TITLE>
</HEAD>
<BODY>
This Document shows the use of JavaScript Arrays
<BR>
<SCRIPT language="JavaScript">
itemNames=new Array("Computer","TV","Radio")
itemPrices=new Array(35000,12000,4500)
document.write("First Item: Name-" + itemNames[0]+", Price-"+itemPrices[0])
document.write("<BR>")
document.write("Second Item: Name-" + itemNames[1]+",Price-"+itemPrices[1])
document.write("<BR>")
document.write("third Item: Name-" + itemNames[2]+", Price-"+itemPrices[2])
</SCRIPT></BODY></HTML>

The output of above example is shown below:

Java Script Array Example


Previous Page Home Page Next Page
ICT Applications