JavaScript Variables

Variables are containers for storing data (values). You can place data into these containers and then refer to the data simply by naming the container.

Variables can be thought of as named containers. It is the basic unit of storage in a program.

JavaScript variable is simply a name of storage location. Variables are just named placeholders for values.

JavaScript variables are loosely typed that means they can hold values with any type of data.

We can use variables to store goodies, visitors, and other data.

Declaring variables in JavaScript

There are 3 ways to declare a JavaScript variable:

  • Using var
  • Using let
  • Using const

In this chapter you will learn about declaring variables using ‘var'.

Variables are declared with the var keyword as follows.

var money;
var name;

You can also declare multiple variables with the same var keyword.

You can declare two or more variables using one statement, each variable declaration is separated by a comma (,) as follows:

var money, name;

Storing a value in a variable is called variable initialization. Variable initialization can be done at the time of variable creation or at a later point in time when you need that variable.

var name = "Anil"; //Variable initialization at the time of variable creation

var money;
money = 2000; //Variable initialization at a later point

You should not re-declare same variable twice.

The value type of a variable can change during the execution of a program and JavaScript takes care of it automatically.

Naming variables

  • Variable name can start with a letter, underscore (_), or dollar sign ($).
  • After the first letter, you can use numbers, as well as letters, underscores, or dollar signs.
  • Don’t use any of JavaScript’s reserved keywords.
  • Names are case sensitive (y and Y are different variables)

Example of JavaScript variable

<!DOCTYPE html>
<html lang="en">

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Example of JavaScript variable</title>

        var x = 10;
        var y = 20;
        var z = x + y;