Web Programming TutorialsJavascript Variables and Arrays

Javascript Variables and Arrays

Today we will learn how to declare and use javascript variables and arrays. We will create a simple html page and then learn different relating concepts along with declaration of varaiables and arrays in it and view the output on the webpage. Let’s start with variables first.
Follow the step by step procedure to learn

  1. Create a new folder on desktop with name “sec2_ch1”.
  2. Now open a new notepad++ document and save it as “var_array.html” in the folder “sec2_ch1” created just now. Select “Save as type” as “Hyper Text Markup Language file (*.html*.htm*.shtm)”.
  3. Write the following code in this “var_array.html” file and save it.
  4. <!DOCTYPE html>
    <html>
    	<head>
    		<title>Variable & Arrays</title>
    	</head>
    	<body>
    	</body>
    </html>
    
    • When we open this page in browser it will look as shown below:
    • output_before_javascript_code
      fig 1

    • The title given in
      <title>---</title>

      tags in head section is shown on the title bar of the browser.

  5. Now let’s turn to variables.
    • Variable is nothing but a location engaged to store a value.
    • This location is given a name for identification, which is called a variable name.
    • Giving a variable name to any location follows certain rules such as,
      • Variable names must begin with a letter.
      • Variable names can also begin with dollar symbol($) or an underscore(_).
      • Variable name is case sensitive. For example: age and Age are two different variables.
    • Creating a variable in javascript is most often referred to as “declaring” a variable.
    • So now, let’s declare variables.
      • We know that when we use any scripting language in .html file, we enclose the code other than html in
        <script>---</script>

        tags.

      • So to declare 2 variable in the head section of html file write the following code below the
        <title>--</title>

        tags.

      • <script>
        	var car="Honda";
        </script>
        
      • Here in the above code we have declared a variable. var is a keyword used to declare a variable. car is the variable name and Honda is the value assigned to car variable.
      • Honda is a string and can be enclosed either in double quotes or single quotes.
      • In javascript you can declare a variable without var keyword also.
      • Just have a look on the code below:
      • <script>
        	car="Honda";
        </script>
        
      • Declaring a variable without var keyword is also right and will work.
      • Now, if you want to print something on the webpage, it should be done in the body section.
      • In javascript, a command document.write(); is used to print anything.
      • So write the following code in body section of the webpage.
      • <script>
        	document.write("Hello World!");
        </script>
        
      • The document.write(); command will print the text “Hello World!” on the webpage as it is as shown below.
      • Hello_World_output
        fig 2

      • Now if we want to print the value stored in the variable car declared above, we should write it as follows:
      • document.write(car);
      • This statement will print the value stored in the variable car as shown below:
      • car_value_output
        fig 3

      • Now if you change the value of car from Honda to Toyota, the statement document.write(); will also print Toyota on the webpage instead of Honda.
    • Let’s give integer values to variables.
      • We know that variables can store different types of values in it. So let’s declare 2 variables containing 2 integer values in head section.
      • var x=5;
        var y=10;
        
      • The variables x and y contains 5 and 10 values respectively.
      • If we want to print its addition, write the following statement in body section.
      • document.write(x+y);
      • You will see that addition of 5 and 10 is printed on the webpage as shown below:
      • addition_of_x_&_y_output
        fig 4

    • Integer values treated as strings:
      • We have seen the declaration of x and y variables above. The values are 5 and 10 are written without any quotes.
      • But if we write these integer values in quotes, they will be treated as strings.
      • Let’s see the demonstration below.
      • Declare 2 different variables in head section.
      • var x1='5';
        var y1='10'; 
        
      • Here, the values 5 and 10 of variables x1 and y1 are enclosed in single quotes.
      • Now write the following statement in body section:
      • document.write(x1+y1);
      • You will get the following output:
      • numbers_in_single_quotes_output
        fig 5

      • The output shown in the above figure is 510.
      • The statement document.write(x1+y1); has just concatenated or joined the two numbers.
      • This is due to enclosing the values 5 and 10 into single quotes. As soon as you enclose numbers in quotes, they no more remain numbers, they transform into strings.
      • So instead of adding them and giving answer as 15, the value of variable y1 is concatenated to the value of variable x1 giving answer as 510.
    • Concatenating string with variables:
      • Just see the following statement:
      • document.write("I have 5 apples.");
      • If we write the above statement in the body section, it will print as it is on the webpage.
      • But I want to print the value stored in the variable x declared somewhere above. To obtain this let’s write the following statement.
      • document.write("I have x apples.");
      • Here, instead of 5 we have used the variable x.
      • Now, let’s see its output:
      • x_apples_output
        fig 6

      • Here, according to the above code, we wished that the x will be replaced with x’s value after execution, but it has been printed as it is.
      • To obtain it we need to use concatenation operator. Plus sign (+) is called as the concatenation operator. It heps us to concatenate or join strings, variables, strings and variables, etc.
      • So to obtain our desired output just use concatenation operator in the above statement as follows:
      • document.write("I have " + x + " apples.");
      • Output is shown as follows:
      • string_variable_concatenation
        fig 7

      • This same concept of concatenation is used to start printing each and every statement on new line in this tutorial.
      • After every printed statement a line brake is applied, so that new statement is printed on new line. An example of this is shown below:
      • document.write(x+y +"<br>");
        document.write("I have x apples.<br>");
      • Here, in the first statement, (x+y) is an expression and to obtain its answer, it is written without quotes, but brake tag should be written in string format because it has to take the cursor to new line. So the expression and the string containing brake tag are concatenated.
      • In the next statement, we are printing a string itself, so brake tag need not require to be placed in separate quotes hence no concatenation here.
    • Some important things about variables:
      • Multiple variables can be created within one statement separating them with comma.
      • Eg: var lastname=”Deo”, age=30, job=”carpenter”;

      • We can span our declaration on multiple lines also.
      • Eg: var lastname=”Deo”,
        age=30,
        job=”carpenter”;

      • If you have declared a variable with a value and later you again declare the same variable. It will retain the value assigned to the variable declared firsr time.
      • For example, if you have declared a variable carname with value “Ford” as :
      • var carname=”Ford”;
      • And now you again declare the same variable without any value as:
      • var carname;
      • This carname variable will retain the value “Ford” assigned during its first time declaration. It will not give any error.

    This was all about variables. Now let’s understand arrays.

  6. Learining about arrays.
    • Array is a data structure which can store multiple values under a single variable.
    • If you want 3 values in your program, it is easy to declare 3 variables.
    • But if you need directly 100 values, it is a stupidity to declare 100 variables, at this situation you can use array.
    • Arrays are declared in 3 ways:
    • First way:
    • var cars = new Array();
    • Here we have created an array object called cars. This is a regular way of creating arrays. It creates an empty array.
    • Array has index to traverse through it. Array index always start from zero (0) onwards.
    • So to store values in above array, we can use the following statements:
    • cars[0]="Ford";
      cars[1]="Toyota";
      cars[2]="BMW";
    • According to the above statements, Ford will be stored at index 0 of cars array, Toyota will be stored at index 1 of cars array and BMW will be stored at index 2 of cars array.
    • Second way:
    • var cars = new Array(“Ford”, ”Toyota”, ”BMW”);
    • Here we have created an array object called cars and have directly assigned values to it . This is a condensed way of creating arrays.
    • According to the above statements, Ford will be stored at index 0 of cars array, Toyota will be stored at index 1 of cars array and BMW will be stored at index 2 of cars array.
    • Third way:
    • var cars =[“Ford”, ”Toyota”, ”BMW”];
    • Here we have directly assigned values to cars. This is a literal way of creating arrays.
    • According to the above statements, Ford will be stored at index 0 of cars array, Toyota will be stored at index 1 of cars array and BMW will be stored at index 2 of cars array.
  7. Printing array values.
    • To print any value in array you can use the following statement.
    • document.write(cars[0] +”<br>”);
      document.write(cars[1] +”<br>”);
      document.write(cars[2] +" ... before changing<br>");
    • This will print the zero’th index value in cars array. i.e “Ford”, array value at index 1 i.e. “Toyota” and array value at index 2 i.e. “BMW”.
    • We can change a value in array at any index by just assigning a new value to that index as shown below:
    • cars[2]=”Dodge”;
    • Here, we have changed the value at index 2 from BMW to Dodge.
    • When you print it, it will show us Dodge.
    • document.write(cars[2] +" ... after changing<br>");
    • The output is shown below:
    • array_element_output
      fig 8

  8. Since arrays are objects they can have methods and properties as well.
    • Some properties are demonstrated below:
    • document.write("number of elements in cars array = " + cars.length + "<br>");
      document.write("index of "Toyota" in cars array = " +    cars.indexOf("Toyota"));
      
    • In the above statements, length and indexOf properties are used to count the number of array elements and to know the index of a particular array element respectively.
    • The output is shown below:
    • array_properties_output
      fig 9

    • In javascript, you are allowed to store different type of elements in single array.

    Here, we finished with our variables and arrays. We will study traversal of arrays using loops in next section.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -