1. Declare Variable in JavaScript
In JavaScript, you can declare a variable using the var keyword. This tells the system to reserve some memory for future use. After declaring the variable, we can store a value in it. For example:
1 2 |
var MyVar; Myvar = 12; |
In the above snippet, we declare a variable called MyVar
using the keyword var. In the next line, we store a value of 12 into the variable MyVar. The = sign denotes the assignment. Means. It tells value 12 is assigned to the variable MyVar. Note, JavaScript is case sensitive and when you read the back the value you have to use the same variable name with the same case.
2. The Declare Variable Example
The example is in the below screenshot. You can use any editor type the code and save it as 001_DeclareVariable.html:

Explanation
1) Within the body
tag, we have a pair of
<Script> &
</Script> tags and the JavaScript code stays in between these tags.
2) In the first code snippet, we declared a variable called MyVar
. Using the assignment operator =, we stored a string value in the MyVar
. Then, using the
alert function, we display the content of the MyVar
in a message box. Note how semicolon in separating each statement for easy readability. But the usage of the semicolon to separate the statement is optional.
3) In this code snippet, we reuse the same variable MyVar and assign an integer value of 108 to it. JavaScript is a weekly typed language. So once a variable is declared, it can store any value in it. Here, in our case, the old value “Some String” is lost, and the variable is now holding the value 108 in it. We once again use the alert method to display the content of the variable, MyVar.
3. Running the Javascript Variable Example
1) Let us assume that you saved the file 001_DeclareVariable.html at C:\Temp folder.
2) Open Google Chrome Browser
3) Navigate to the Folder C:\Temp
4) Drag & Drop the File 001_DeclareVariable.html to Chrome Browser
5) The browser shows the Message Box thrown by the alert call. Message box shows the MyVar variable content:

6) Click OK on to the message box. The second alert display which shows the MyVar variable’s updated content:

4. Code Reference
001_DeclareVariable.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<!DOCTYPE html> <html lang="en"> <head> <title>Declare and Use variables</title> </head> <body> <script> //Sample 01: Read and Write Variable var MyVar = "Some String"; alert(MyVar); //Sample 02: Reuse Same variable with Different Type MyVar = 108; alert(MyVar); </script> </body> </html> |
Categories: JavaScript