JavaScript variables
JavaScript

JavaScript variables

Mishel Shaji
Mishel Shaji

In programming, a variable is a value that can be changed. All variables will have a storage location and a name. The variable name is usually used to refer to the value that is stored in a variable.

Creating JavaScript variables

In JavaScript, you must declare a variable before using it. A variable is declared using the var keyword.

<script type="text/javascript">
var a;
//you can declare multiple variables as follows:
var b, c;
</script>

Assigning a value

A value is assigned to a variable using the = operator.

<script type="text/javascript">
var a = 10;
var b = 10.5;
var c = "John";
</script>

Assigning value to a variable is known as initialization. In JavaScript, you can initialize a variable during deceleration or later.

<script type="text/javascript">
var a = 10; //A variable is declared and initialized.
var b; //A variable is declared but not initialized.
b = "John"; //Variable is initialized.
</script>

Things to remember

  • An uninitialized variable variable will have the value undefined.
  • A variable will not lose it’s value if it is declared again.
  • Never use quotes for storing a numerical value.

Numbers as strings

If you put any numbers in quotes, the remaining numbers will be treated as a string.

Example

<!DOCTYPE html>
<html>
<head>
    <title>JS examples</title>
</head>
<body>
    <p id="txt"></p>
    <script type="text/javascript">
    var a = "10" + 5;
    var b = 5 + 2 + "3";
    var c = "The value of a is: "+ a + " and the value of b is: "+ b;
    document.getElementById("txt").innerHTML = c;
    </script>
</body>
</html>

Output

The value of a is: 105 and the value of b is: 73