JavaScript - Declaring and Using Variables

Introduction to Java Script

 
Java Script is a scripting language and it can run on the Server-Side or Client-Side. When it runs on the client side, it is executed by the client browsers and when it runs on the server side, the web server runs the scripted code.
 
Unlike C++ and Java, Java Script is an interpreted language. This means, the script is processed line by line. Remember, it can run on the Server or client’s web browser. Java script comes with various built-in objects using which one can generate dynamic HTML, validate user input, style the html elements etc. In this article we are going to write our first Java Script code.
 
Pre-Requisites for Java Script
 
To write Java Script, we need the following,
  1. Notepad++ (Or any other editor)
  2. Chrome or IE Browser
The latest versions of browsers support the latest features in Java script. So have the latest browser so that you can learn all the capabilities of the Java Script. Let us start our first Java Script.
 

Declaring a Variable

 
You can declare a variable using var keyword. Since it is scripting language we don't need to specify the data type for it. Have a look at the below code snippet,
  1. var Calculated_Result;  
Here, the variable Calculated_Result is declared. But, if you notice, we do not specify any type like int, float. This means, a variable in java script can hold any type of data in it. In Java Script, a variable is just a name for a memory location.
  1. var Calculated_result;  
  2. Calculated_result = 15;  
  3. Calculated_result = "Nothing";   
In the above code, you can see how a variable is holding an integer as well as string value.
 

Our First Java Script

 
Have a look at the below code snippet,
 
At line number 7, we declared a variable and initialized it to a string value. Note, the variable is type-less and you can store any data type in it. The ‘document’ is an object available to Java Script. This object represents the html document in which the script is running. The write method is used to write something in the html document. Here we appended the variable name with ‘Welcome Mr.’ and printed that in the html page. You can save the above content as ‘MyFirst.html’ and when it opens this in IE or Chrome it will print the contents written by the ‘document.write’ function.
 
Below is the screenshot of the example,
 
Code Listing
  1. <!DOCTYPE HTML>  
  2.    <HTML>  
  3.       <HEAD>  
  4.          <TITLE>Learn Java Script</TITLE>  
  5.       </HEAD>  
  6.    <BODY>  
  7.       Here is My First Java Script: <br/>  
  8.       <script type="text/javascript" >  
  9.          var Name = "Ganapathy Sundram";  
  10.          document.write("Welcome Mr. " + Name);  
  11.       </script>  
  12.    </BODY>  
  13. </HTML>