• JavaScript Video Tutorials

JavaScript - Variables



JavaScript Variables

JavaScript variables are used to store data that can be changed later on. These variables can be thought of as named containers. You can place data into these containers and then refer to the data simply by naming the container.

Before you use a variable in a JavaScript program, you must declare it. In JavaScript, you can declare the variables in 4 ways −

  • Without using any keywords.

  • Using the 'var' keyword.

  • Using the 'let' keyword.

  • Using the 'const' keyword.

The let and const keywords were introduced to JavaScript in 2015 (ES6). Prior to ES6, only var keyword was used to declare the variable in JavaScript. In this section, we will discuss 'var' keyword. We will cover the 'let' and 'const' keywords in subsequent chapters.

Variable Declaration in JavaScript

You can follow the syntax below to declare the variables without using any keywords.

<script>
   Money = 10;
   Name = "tutorialspoint";
</script>

Furthermore, you can use the var keyword to declare the variables as shown below.

<script>
   var money;
   var name;
</script>

You can also declare multiple variables with the same var keyword as follows −

<script>
   var money, name;
</script>

Variable Initialization using the Assignment Operator

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

For instance, you might create a variable named money and assign the value 2000.50 to it later. For another variable, you can assign a value at the time of initialization as follows.

<script>
   var name = "Ali";
   var money;
   money = 2000.50;
</script>

Note − Use the var keyword only for declaration or initialization, once for the life of any variable name in a document. You should not re-declare same variable twice.

JavaScript is untyped language. This means that a JavaScript variable can hold a value of any data type. Unlike many other languages, you don't have to tell JavaScript during variable declaration what type of value the variable will hold. The value type of a variable can change during the execution of a program and JavaScript takes care of it automatically.

JavaScript Data Types

In JavaScript, the variable can hold the value of the dynamic data type. For example, you can store the value of number, string, boolean, object, etc. data type values in JavaScript variables.

<script>
   var num = 765; // Number
   var str = "Welcome"; // String
   var bool = false; // Boolean
</script>

You will learn data types in detail in JavaScript Data Types chapter.

JavaScript Variable Names (Identifiers)

In JavaScript, a unique character sequence is used to name the variables called identifiers.

Here are some rules for the naming of the identifiers in JavaScript −

  • Valid characters − In JavaScript, a variable name can contain digits, alphabetical characters, and special characters like underscore (_) and dollar sign ($). JavaScript variable names should not start with a numeral (0-9). They must begin with a letter or an underscore character. For example, 123test is an invalid variable name but _123test is a valid one..

  • Case sensitivity − Variable names are case sensitive. It means Name and name are different identifiers.

  • Unicode support − The identifiers can also contain the Unicode. So, developers may define variables in any language.

  • Reserve keywords − You should not use any of the JavaScript reserved keywords as a variable name. For example, break or boolean variable names are not valid. Here, we have given a full list of the JavaScript revered keywords.

JavaScript Dollar Sign ($) and Under Score (_)

You can use the $ and _ to define the variables in JavaScript, as the JavaScript engine considers it a valid character.

Example (Demonstrating the identifiers)

In this example, we have defined the variables using the var keyword. The first variable name starts with the underscore, and the second variable name starts with the dollar sign. Programmers can uncomment the third variable declaration to check the error generated by JavaScript when we start any identifier with the digit.

<html>
<head>
    <title> Variables in JavaScript </title>
</head>
<body>
   <script>
        var _abc = "Hi!";
        var $abc = "Hello!";
        //  var 9abc = "Bye!";  // This is invalid
        document.write("_abc " + _abc + "<br>");
        document.write("$abc = " + $abc + "<br>");
    </script>
</body>
</html>

It produces the following result −

_abc Hi!
$abc = Hello!

Undefined Variable Value in JavaScript

When you don't initialize the variable after declaring, it contains the undefined value. However, you can also assign the undefined value to the variable.

Let's look at the example below.

Example

<html>
<body>
   <script>
      var num;
      document.write("The value of num is: " + num + "<br/>");
   </script>
</body>
</html>

This produces the following result −

The value of num is: undefined

JavaScript Variable Scope

The scope of a variable is the region of your program in which it is defined. JavaScript variables have only two scopes.

  • Global Variables − A global variable has global scope which means it can be defined anywhere in your JavaScript code.

  • Local Variables − A local variable will be visible only within a function where it is defined. Function parameters are always local to that function.

Within the body of a function, a local variable takes precedence over a global variable with the same name. If you declare a local variable or function parameter with the same name as a global variable, you effectively hide the global variable. Take a look into the following example.

Example

In the example below, we have defined the variable named myVar outside the function and initialized it with the 'global' value. Also, we have defined the variable with the same identifier inside the checkscope() function and initialized it with the 'local' value.

We print the myVar variable's value inside the function. So, the local variable takes preference over the global variable and prints the 'local' in the output.

<html>
<head>
   <title> JavaScript Variable Scope Example</title>
</head>
<body onload = checkscope();>   
   <script>
	  var myVar = "global";      // Declare a global variable
	  function checkscope( ) {
		 var myVar = "local";    // Declare a local variable
		 document.write(myVar);
	  }
   </script>     
</body>
</html>

This produces the following result −

local

Example

In the example below, we have defined the variables without using the var keyword. The name variable contains the value of the string type, and the number variable contains the value of the float data type.

When we define the variables without using any keyword, JavaScript considers them global variables and can use them anywhere inside the code.

<html>
<head>
   <title> Variables without var keyword </title>
</head>
<body>
   <script>
      name = "tutorialspoint"; // String type variable
      number = 10.25; // Number type variable
      document.write("name = " + name + ", number = " + number + "<br>");
   </script>
</body>
</html>

This produces the following result −

name = tutorialspoint, number = 10.25

Also, the identifier doesn't lose the previous value if we declare the variable using the var keyword with the value and re-declare the same identifier without initialization. Let’s understand it via the example below.

Example

In the example below, we have declared the age variable and initialized it with 10. Again, we have declared the age variable but haven’t initialized it. Still, it prints 10 in the output because it doesn’t lose the previous initialization’s value. However, if we update the value of the age variable, it successfully updates it.

<html>
<head>
   <title> Variables with var keyword </title>
</head>
<body>
   <script>
      var age = 10;
      var age;
      document.write("age = " + age + "<br>");
   </script>
</body>
</html>

This produces the following result −

age = 10
Advertisements