JavaScript Variables

In JavaScript, variables are containers that hold data.

JavaScript allows a variable to hold any type of data. In other words, we can initialize a variable with a numeric value, and then assign a string value, etc.

Declaration

To declare a variable, use var keyword followed by the variable name, as shown in the following syntax.

</>
Copy
var x;

where var is the keyword and x is the name of the variable using which we can reference the value stored in it.

We can declare multiple variables in a single statement using comma separator.

In the following statement, we declared two variables: x and y.

</>
Copy
var x, y;

Initialization

To initialize a variable, use assignment operator and assign a value to the variable.

</>
Copy
var x = 2;

Here, we have assigned a value of 2 to the variable x. Also, we have declared the variable and assigned a value to it in a single statement. We may separate the declaration and initialization as shown in the following.

</>
Copy
var x;
x = 2;

In the following example, we initialize a variable x with string value "Hello World" and assign it to the inner HTML of a HTML element.

index.html

</>
Copy
<!DOCTYPE html>
<html lang="en">
<body>
    <pre id="output"></pre>
    <script>
        var x;
        x = 'Hello World';
        document.getElementById('output').innerHTML += x;
    </script>
</body>
</html>

Initialize Multiple Variables in a Single Statement

We can also declare/initialize multiple variables in a single statement. Use comma separator, to separate the variable initialisations.

index.html

</>
Copy
<!DOCTYPE html>
<html lang="en">
<body>
    <pre id="output"></pre>
    <script>
        var x, y;
        x = 'Apple', y = 'Banana';
        document.getElementById('output').innerHTML += x + '\n';
        document.getElementById('output').innerHTML += y;
    </script>
</body>
</html>

Default Value of a Variable

If a variable is not initialized, then the variable returns undefined when read.

index.html

</>
Copy
<!DOCTYPE html>
<html lang="en">
<body>
    <pre id="output"></pre>
    <script>
        var a;
        document.getElementById('output').innerHTML += a;
    </script>
</body>
</html>

Conclusion

In this JavaScript Tutorial, we learned what Variables are, how to declare/initialize them, and how to use them in a program, with examples.