Declaring Variables in Javascript  

Variables are used to store and retrieve data, also known as values. A variable can refer to a value, which changes or is changed. Language Javascript is case sensitive (i.e. A != a and Z != z).

0 330 Technology | Javascript
Wed Dec 26 , 2018

A Javascript identifier must start with a letter or underscore(_); subsequent characters can also be digits(0-9).

In this article we will discuss how we declare variables in javascript.

You can declare a variable with the var statement.


<script type = "text/javascript">
var var1="some value";
Or like this:

<script type = "text/javascript">
var var2;
var2="some value";

Here, the variable name is on the left side of the expression and the value you want to assign to the variable is on to the right side.

You can assign a value to a variable like this:

<script type = "text/javascript">
var var1="Hello";
Or like this:

<script type = "text/javascript">
var var2;



<h2>JavaScript Variables</h2>
<p>In this example, a, b, and c are variables.</p>

var a = 5;
var b = 6;
var c = a * b;
document.write("The value of c is: " + c);



Life span of variables

When you declare a variable within a function, the variable can be accessed only within that function. When you exit the function, the variable is destroyed. These variables are called local variables. You can have local variables with the same name in different functions, because each is recognised only by the function in which it is declared.

If you declare a variable outside a function, all the functions on your page can access it. These variables are calledglobal variables. The lifetime of these variables starts when they are declared, and ends when the page is closed.

Subscribe & Get Regular Updates On Your E-mail