Javascript Variables & Constants Tutorial

In this Javascript tutorial we learn about variables and constants. Single element temporary data containers that can be either be changed or must stay constant.

We cover how to declare and initialize, mutate and use variables and constants.

Here's a table of contents of what you'll learn in this lesson:
(click on a link to skip to its section)

Let's jump right in.

What is a variable

A variable is a data container that stores behind-the-scenes data temporarily in a system’s memory (RAM) while the program runs. We give these variables meaningful names to allow us to easily work with the data inside.

A variable can store a single type of data, such as a string of characters that form a sentence or a number.

In many other programming languages such as C or C#, we must explicitly declare what type of data the variable will hold. In Javascript however, the translator will automatically infer the data type from the value stored inside the variable.

How to declare a variable

To declare a variable, we write the keyword var , followed by the name we want to give the variable and we terminate the statement with a semicolon ( ; ).

Syntax:
var unique_name;

This will create an empty variable with whatever unique name we give it. This variable is now ready to accept data to store.

Example:
var message;

How to assign data to a variable

Now that we have a variable, we can add some data inside of it. To assign data to a variable, we write its name, followed by the = operator and then any data we want to give it. Lastly, we end the statement with a semicolon again.

Syntax:
unique_name = value;

Now the variable will have data stored inside it and we can use it.

Example:
// declaration
var message;

// assign data
message = "Hello World";

How to initialize a variable with a value

If we know the data we want to store beforehand, we can directly assign data to the variable when we declare it. This is called variable initialization.

To initialize a variable, we write the var keyword and the name we want to give it, then the assignment operator ( = ) and the data we want to assign to the variable. This statement needs to be ended with a semicolon as well.

Syntax:
var unique_name = data;
Example:
// initialization
var message = "Hello World";

How to use a variable

To use a variable, we simply refer to it by its name. The translator will pull the data from the variable and substitute it wherever we use it.

We can modify the code from our first application.

Example:
<script>

  var message = "Hello World";

  document.write(message);
  // document.write("Hello World");

</script>

In the example above, we create a variable called message with the words “Hello World”. Where we previously wrote the words directly into the document.write() function, we now write the variable name.

When we save the document and open it in the browser, we can see that the words inside the variable are displayed on the page.

As another example, let’s do some simple math with variables.

Example:
<script>

  var x = 5;
  var y = 3;
  var result = x + y;

  document.write("5 + 3 = ", result);

</script>

In the example above, we add the value of y to the value of x and store the result in a variable called result. Then we print the result to the webpage.

So the translator substitutes the variable name with its value. The example above would essentially look like this.

Example:
8 = 5 + 3
document.write("5 + 3 = ", 8);

How to change data in a variable

A variable is mutable, which means that we can change the data inside the variable at any time we need. We don’t have to set up a new variable each time we need data.

To change, or mutate, the data inside a variable, we simply assign the new data to it with the assignment operator.

Example:
<script>

  var message = "<p>Hello World</p>";
  document.write(message);

  // mutate data
  message = "<p>Greetings</p>";
  document.write(message);

</script>

In the example above, we mutate the message variable to hold a new value.

What is a constant

A constant is the same as a variable except that it’s value cannot change during runtime.

This is useful so that the application doesn’t accidentally change a value that shouldn’t be changed, such as the value of pi or gravity.

How to declare/initialize a constant

We cannot declare a constant without a value. If we want to create a constant, we must initialize it with a value.

To initialize a constant, we use the keyword const instead of the keyword var.

Syntax:
const UNIQUE_NAME = value;

We write the name in all capital letters as a convention. It allows us to easily distinguish between regular variables and constants.

Example:
const PI = 3.14;

How to use a constant

Using a constant is the same as using a variable. We simply refer to the constant’s name where we need to.

Example:
<script>

  const PI = 3.14;
  var radius = 3;

  // calculate the area of a circle
  var area = PI * radius * radius;

  document.write(area);

</script>

In the example above, we use the constant PI to calculate the area of a circle.

Variable & Constant naming rules and conventions

There are a few rules we should consider when naming our variables and constants.

  1. A name must start with a letter (a to z or A to Z), an underscore ( _ ), or a dollar sign ( $ ).
  2. A name cannot start with a number, but may contain numbers.
  3. A name cannot be the same as a Javascript keyword.
  4. Names are case sensitive. For example var a and var A are different variables.
Example:
// correct
var message;
var _message;
var $message;
// incorrect
var #LostSock#TheStruggleIsReal;
var (^_^);

// correct
var MamboNumber5;
// incorrect
var 21JumpStreet;

// correct
var a_unique_name;
// incorrect
var const;

// case sensitive
var learning;
var Learning;
var LEARNING;

It’s also a good idea to always follow the naming conventions, especially when working as part of a team.

  1. Variable names should use snake_case. All letters of the name is lowercase and multiple words are separated by underscores.
  2. Constant names should be in ALL_CAPS and multiple should also be separated by underscores.
  3. Names should not be abbreviated.
  4. Names should be singular, not plural.
Example:
// correct
var this_is_a_variable;
const THIS_IS_A_CONSTANT;
// incorrect
var ThisIsPascalCaseNaming;
var thisIsCamelCaseNaming;

// correct
var delete_me;
// incorrect
var del_me;

//correct
var employee_list;
// incorrect
var employees;

It should be noted though that you may be required to follow different conventions by your employer. It doesn’t really matter which convention you follow, the key is consistency.

In this tutorial course we will be following the conventions above, as well as some others that we’ll get to when needed.

Summary: Points to remember

  • Variables and constants are temporary data containers, when the application stops (for whatever reason) the data inside is lost.
  • Variables can be mutated at runtime, whereas constants cannot.
  • Variables use the var keyword at declaration and initialization, and constants use the const keyword.
  • Constants cannot be empty, they must be initialized with a value.