Friday, 29 November 2013

JavaScript Variables-Storage & Declaration

Now we have understood how simple scripting in JavaScript is written.

Let us take in some input from the user using the prompt(); function.
  • prompt(); function:
The prompt function prompts the user to input data into it by providing a textbox.You also get two buttons to input your reaction.Hence the interactivity.

Now the website has asked the input data, now let it process it and act upon it.

You have entered the data asked by the webpage prompt, now let us store it in a variable.

Storing the data directly upon entering is done using the variable declaration along with the prompt input function separated by a "=" sign.
var num = prompt("Enter a number");

In JavaScript variables are declared using the "var" keyword. Any variable can be created using this keyword, irrespective of the type of data it stores viz.textual,numerical,symbolical,patterns.

Sample variable declaration
var num;
var name;
var pattern;

The above three declarations can be further assigned specific values by the user.
Sample variable assignment
  1. The first assignment assigns a numerical value of 10 to the variable num.
  2. The second assignment assigns a textual value of Javascript to the varialble name.
  3. The third assignment is a bit peculiar in nature, as the name of the variable suggests it is a pattern, it can intelligently identify the digits between 0 to 9 including 0 and 9 both.
    In general it is called a 'REGULAR EXPRESSIONS'.
    Using such regular expressions one can design their own intelligent variables.
    Let us revisit this in more depth in a while after we visit functions.

    I would suggest you to have a look at what Regular Expressions are here before we approach them, as it would be helpful to have a more intelligent and creative session with them.

    The sample program below showcases the declaration and storage of variables.

1:  <?xml version = "1.0" encoding="utf-8"?>   
2:  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"   
3:  "">   
4:  <html xmlns = "">   
5:  <head>  
6:  <title>JavaScript </title>  
7:  </head>  
8:  <body>  
9:  <script>  
10:  var num = prompt("Enter a numbe r");  
11:  var name = "JavaScript";  
12:  alert("The number you entered now was" +num);  
13:  document.write("I am "+name);  
14:  </script>  
15:  </body>  
16:  </html>  

No comments :