JavaScript Variables | Declaration, Example

A variable in JavaScript is a container that can hold a value such as a number, some text string, an element in the DOM, a function, an object, or anything.

In other words, a variable is a kind of data (or information) container where we can store data into the container and then refer to this data by simply naming the container.

In simple words, we use JavaScript variables to store values or expressions. For example, a numeric variable can store a single number, a string, just a sequence of characters.

Variables in JavaScript

Variables are useful because they can store data in one part of the program, and can be used that data elsewhere later. The value of a variable can also change with the circumstances as the program executes.

For example, imagine a JavaScript-based cricket game where the goal is to get the highest score.

When a player first starts to play a cricket game, his score will be 0 but as he runs by hitting the ball by bat, he makes runs, and the score gets ahead.

Here, score is a variable because it starts at 0 but changes as the game progress. Hence, variable holds data that can change under varying conditions.

Variables Declaration in JavaScript


We declare variables in JavaScript with only the var keyword, followed by the name. Declaring a variable means to tell the JavaScript interpreter to reserve the space in the memory for the variable.

The general syntax to declare a variable in JavaScript is as follows:

var variableName; // Here, variableName is the variable's name.

For example, the following line of code creates a variable named name.

var name;

The following are all valid variable declarations:

1. var x;
2. var myVar;
3. var myText;
4. var counter1;

In JavaScript, we can also declare multiple variable names together with a comma-separated list. For example, the following statements declare three variables named firstName, lastName, and age.

var firstName, lastName, age;

There are a few rules that should keep in mind when declaring variables. They are:

1. Variable names must start with uppercase, lowercase letters, $, or _. That is, the first character must be with either a letter or an underscore character (_).

2. The remaining (i.e. subsequent) characters can be letters, numbers, underscore characters, or a dollar sign ($).

3. Variable names cannot begin with a number or punctuation.

4. They cannot contain spaces or other punctuations. They may not contain special characters (e.g., ! . , / \ + * =).

5. An identifier cannot be variable names. Reserved words (like JavaScript keywords) are basically the words that develop the JavaScript language. They cannot be variable names.

6. JavaScript is case-sensitive. As a result, upper case letters differ from lowercase letters.

For example, student, Student, and STUDENT are the names of three different variables. Avoid using such similar identifiers in the same script.

The following variable names are invalid:

1. var 1stCounter; // cannot start with digit.
2. var new variable; // cannot have space.
3. ^mystring // first character is illegal
4. var var; // keyword.
5. var document; // keyword.
6. var length; // keyword.

The following variable names are valid:

1. var myText;
2. var $;
3. var r8;
4. var _counter;
5. var $field;
6. var __$abc;
7. var my_School;

The semicolon is used to terminate a statement. It is not required, but it is good practice to use it always.

Variables Initialization in JavaScript


Once a variable has declared or created, the next task is to assign (give) or initialize a value to it. The process of assigning an initial value to a variable is called initialization.

We can initialize a variable with value using the assignment operator: equal sign (=). The general syntax to initialize a value to a variable is as follows:

var variableName = initialValue;

In the above syntax, variableName is the variable name and initialValue is the value assigned to the variable.


For example, the following statements declare variables with initial values.

var name = "Shubh"; // Here, we are assigning a string value to a variable name.
var age = 20;

We can also initialize a value to a variable (after declared) in the following fashion:

a) var age; // creating a variable age.
     age = 30; // storing the number 30 in that variable.

b) var myText;
    myText = "Hello world!";

We can also declare multiple variables on the same line of code, as follows:

var x, y, firstName, lastName;

These variables can be initialized at the same line of code, too, like this:

var x = 10, y = 20, firstName = "Shubh", lastName = "Deep";

Variable types in JavaScript


Most high-level languages such as C and Java are strongly typed. It means that when we declare a variable in a program, we must declare its type of variable before it used. Once a variable has defined, we cannot change its data type.

Variables in JavaScript are weakly types (i.e. not strongly typed). It means that a variable will hold an integer, a floating-point number, or a string simultaneously.

We can also change the value of a variable through simple reassignment.

Consider the below example, where the variable x first holds an integer value but then, through another assignment, it changes to hold a string value:

var x = 20;
x = "Now it is a string.";

Thus, we can change the value of a variable whenever we want. Consider another example to understand better.

var myText;
myText = "Hello Javascript";
myText = 99;
myText = 4 * 10;
myText = true;
myText = undefined;

Using Variables in Statements


Once we declared a variable and assigned a value to it, we can then use that variable in other statements. When Javascript interpreter embedded in the web browser sees the variable, it goes to the computer’s memory, retrieves the current variable’s value, and then puts that value into the statements.

1. Let’s take a very simple example program where we will declare a variable and assign value to it, and then use it in another statement. Look at the script code to understand better.

Program code 1:

<script>
 // Declaration and initialization of a variable.
    var firstName = "Ivaan";
    document.write("Welcome to Scientech Easy! " +firstName);
</script>
Output:
      Welcome to Scientech Easy! Ivaan

This script uses write() method to simply display the current value of a variable.


2. Let’s take another simple, slightly different examples where we will initialize the variable by taking the input from the user using prompt() method.

Program code 2:

<script>
  var firstName;
      firstName = prompt("Please, tell me your first name");
    document.write("Welcome to Scientech Easy! " +firstName);
</script>
Output:
          Welcome to Scientech Easy! Ivaan

In the above script, the prompt() method has been used to ask the user to enter his first name, as shown in the top browser. When the user enters his name and clicks on ok button, JavaScript interpreter stores his name in firstName variable.

The script then uses write() method to display the welcome message using the value of firstName variable.


3. Let’s create a program where we will declare a variable and assign a value to it and then display the value. After it, we will change the value, again display it, and so on. Look at the script code to understand better.

Program code 3:

<script>
   var firstName;
   firstName = "Ivaan";
   document.write(firstName);
   document.write("<br>");
   firstName = "Hege";
   document.write(firstName);
   document.write("<br>");
   firstName = "Deep";
   document.write(firstName);
</script>
Output:
       Ivaan
       Hege
       Deep

This script declares a variable, assigns a value to it, displays the value on the web browser, changes the value, and displays the value again on the web browser.

Redeclaring JavaScript Variables


If we redeclare a variable in JavaScript, it will not lose its original value. For example:

var x = 20;
var x; // redeclaration.

After the execution of the first line of code, the variable x will still have the value 20. The value of x is not clear or reset while redeclared.


Hope that tutorial has elaborated almost all the important points related to variables in JavaScript with example programs. I hope you will have understood the basic concepts of variable declaration and initialization.

In the next tutorial, we will discuss types of variables in JavaScript and their scopes.
Thanks for reading!!!
Next ⇒ Types of Variables in JavaScript⇐ Prev Next ⇒