Pure JavaScript1


[Variable Scope]  [Strings as Array Indexes]  [Multidim Arrays]  [Arrays as Objects]  [JavaScript Home] [Web Home]
Naming and Assigning Variables
Variable declaration without assignment Variable assignment without declaration Variable declaration and assignment Display the results The following line is produced by JavaScript using the above declared variables.


Variable Scope
A variable can be either global or local.  All variables are global unless they are declared (var) in a function, in which case the variable is local to that function. It is possible for two variables with the same name to exist if one is global and the other is local to a function. The following code declares two global variables, colour and size. The monitorSpec() function creates a new variable called size that only exists within the scope of the function. Because the function does not specify var, the global variable colour is changed from green to purple. In addition, a new global variable, price, is declared within the function because the word var is not used.

Computer monitor specification example
//Initialise global variables //Declare a monitor specification function //Declare and set variables inside a function //Display results of monitorSpec() function //Display variable values outside of a function

Using Strings for Array Indexes

E.g. SUITCASE INVENTORY

//Populate an array with suitcase contents

//Display suitcase quantities //Create a clothes quantity array //Set clothes quantities //Display the clothes quantities The following contents list is derived from variables assigned in the above JavaScript array




Multidimensional Arrays

To create multidimensional arrays in JavaScript, the element of an array must be another array.  The inner aray can be accessed by putting two [ ] operators back to back.  The following example shows that to access the brake parts list double [ ] operators are used and the list is displayed in a table.

E.g. Brake Parts Inventory List

//Display brake part inventory in a table

//Display each part //Display all information for each part //Create a brake parts inventory list using a multidimensional array //Display the inventory of brake parts


Arrays as Objects

Because arrays are essentially JavaScript objects, it is possible to access the elements of the arrays as properties if a string index is used.  Dot notation is used, rather than the [ ]  operators.  Both tht [ ] operators and the dot notation are interchangeable when accessing an array, even in the same coding see the following example:

E.g Suitcase Contents

//Populate an array with suitcase contents


JavaScript 1.0 Arrays

JavaScript 1.0 version originally used the Object() constructor to create arrays and because the properties of an Object() could be accessed using the [ ] operator, it was possible to give the illusion of an array