JavaScript Variables

What are Variables?

Variables are containers for storing data (storing data values).

In the following example, xy, and z, are variables, declared with the var keyword:

Example:

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Variables</h1>
<p>In this example, x, y, and z are variables.</p>

<p id="demo"></p>

<script>
var x = 5;
var y = 6;
var z = x + y;
document.getElementById("demo").innerHTML =
 "The value of z is: " + z;
</script>

</body>
</html>


Ways to Declare a JavaScript Variable

There is 4 ways to declare variable in JavaScript:

  • Using var (used in all JavaScript code from 1995 to 2015.If you want your code to run in older browser, you must use var.)
  • Using let ()
  • Using const (constant values and cannot be changed)
  • Using nothing

The let and const keywords were added to JavaScript in 2015.

JavaScript Identifiers

All JavaScript variables must be identified with unique names. These unique names are called identifiers.

Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).

The general rules for constructing names for variables (unique identifiers) are:

  • Names can contain letters, digits, underscores, and dollar signs.
  • Names must begin with a letter
  • Names can also begin with $ and _ (but we will not use it in this tutorial)
  • Names are case sensitive (y and Y are different variables)
  • Reserved words (like JavaScript keywords) cannot be used as names

JavaScript Data Types

JavaScript can handle many types of data, but for now, just think of numbers and strings.

Strings are written inside double or single quotes.

Numbers are written without quotes.

If you put a number in quotes, it will be treated as a text string.

Example:

const pi = 3.14;
let person = “John Doe”;
let answer = ‘Yes I am!’;

How to Declare Variable in JavaScript

It’s a good programming practice to declare all variables at the beginning of a script.

Creating a variable in JavaScript is called “declaring” a variable. You declare a JavaScript variable with the var or the let keyword:

var carName;

OR:

let carName;

After the declaration, the variable has no value (technically it is undefined).

To assign a value to the variable, use the equal sign:

carName = “Volvo”;

You can also assign a value to the variable when you declare it:

let carName = “Volvo”;

In the example below, we create a variable called carName and assign the value “Volvo” to it.

Then we “output” the value inside an HTML paragraph with id=”demo”:

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Variables</h1>

<p>Create a variable, assign a value to it, and display it:</p>

<p id="demo"></p>

<script>
let carName = "Volvo";
document.getElementById("demo").innerHTML = carName;
</script>

</body>
</html>