Each programming language has a fundamental need to store data in memory for doing some computations on that data. Now to store and access this data, the memory location needs a name, and this name is called "Variable". In addition to this, each memory location can store only a specific type of data. And the "DataType" of the variable helps in identifying this. Therefore, in a nutshell, as each programming language has to do some bit of computation, it allows defining, and declaration of variables of specific data types, and JavaScript also follows the same tradition.

In this article, let us deep-dive into a better understanding of  DataTypes and Variables covering across the following topics:

  • What are DataTypes in JavaScript?
    • What are Primitive Data Types in JavaScript?
    • Understanding Composite Data Types in JavaScript?
  • What are Variables in JavaScript?
    • How to define, declare and initialiaze a variable in JavaScript?

    • How to declare and initialize the variable together?

    • Procedure to define multiple variables in a single step in JavaScript?

    • How to redeclare variables in JavaScript?

    • What are the rules for Variable Naming conventions in JavaScript?

    • How to access a JavaScript Variable?

    • What is the Scope of Variables in JavaScript?

What are Datatypes in JavaScript?

data type is a classification of data that tells the compiler or interpreter how the programmer wants to use the data. The values define a specific kind of data item it can take, the programming language it uses, or the operations that can perform on it. Moreover, different data items can be numerical values, alphanumeric values, decimals, boolean, etc.

As we know that JavaScript is a dynamic type (loosely typed) language. Which, in turn, means that users needn't explicitly specify the type of data to store in a variable. The JavaScript engine will dynamically use it based on the type of data assigned to the variable. Additionally, the JavaScript can handle many types of data, and based on that; we can categorize all the supported dataTypes by JavaScript into two types:

  • First, Primitive Data Types.
  • Second, Composite Data Types.

 DataTypes in JavaScript - Copy

Let's understand the details of all these data types in the following sections.

What are Primitive Data Types in JavaScript?:

These are the predefined types of data that are supported by the programming language. JavaScript mainly supports the following types of primitive data types.

  • Boolean: logical entity having values as true or false.
  • Numbers: Represents numeric values and can store integers and decimals.
  • Strings: Represent a sequence of characters such as  “Hello World”. Strings can store in single quotes or double-quotes.
  • Undefined: A variable that has an unassigned value will have an undefined default value.
  • Null: In JavaScript, null means"nothing". It is something that doesn't exist.

What are Composite Data Types in JavaScript?:

The programming language does not predefine these data types, but instead, the programmer creates it. Additionally, the composite data types come into existence when the grouping of multiple values happens. Few of the JavaScript supported composite DataTypes are:

  • Object: It is an instance of a class that accesses the data and members encapsulated in the class.

  • Arrays: It is a group of similar kinds of values.

We will cover the details of all these Composite data types in future articles. Let's move further to understand the concept of a variable and how to declare the same in JavaScript.

What are Variables in JavaScript?

Variables are just the name of the storage location. Moreover, we can also call them as containers that hold some data during the program execution.

Let's understand the concept in more detail with the help of the following examples:

 Variables in JavaScript - Copy

In the above example, "digit" is a variable which points to a memory location which holds/stores the numeric value "12". Similarly, "lang" is a variable which points to the memory location which stores the string value "javascript". So we can say that a variable is just a name to the memory location, where the value will be stored.

As in most of the programming languages, the following facts are true for variables in JavaScript also:

  • All the variables must be declared before one can use them.
  • Moreover, the value stored in a variable is dynamic and can be changed anytime during the program execution.
  • Additionally, a variable is just a named memory location; all the operations done on the variable directly affects that memory location.

How to define a variable in JavaScript?

Like other programming languages, defining a variable in JavaScript follows the below lifecycle:  Declaration Initialisation Assigment of JavaScript Variable - Copy

Let's discuss and understand all these phases of variable definition in the below sections.

How to declare a variable in JavaScript?

Similar to other programming languages, creating a variable is called as "Declaring" a variable in JavaScript. In addition to this, the declaration of the variable happens with the help of the "var" keyword.  Declaring a variable in JavaScript - Copy

Example

var test;

where the test is the name of the declared variable.

How to initialize a variable in JavaScript?

After the declaration, we can use the equal(=) sign to assign value to the variable:

Variable initialization in JavaScript - Copy

Example:

test = 10;

where the test is the name of the variable and is assigned a value of 10.

How to declare and initialize the variable together?

We can also assign the value to the variable at the same time as its declaration:  Variable declaration and initialization

Example:

var test = 10;

where var is the keyword to declare the variable, and the test is the name of the variable, and the assigned value is 10.

How to define multiple variables in a single step in JavaScript?

JavaScript also allows declaring multiple variables in one line:  Multiple variables in JavaScript

Example:

var test1 = "John", test2 = "Dheer", test3 = 200;

The same declaration can even span across multiple lines, as shown below:

var test1 = "John",
test2 = "Dheer",
test3 = 200;

How to Redeclare Variables in JavaScript?

JavaScript variable always persists its value throughout the scope, even though we again declare the same.

Eg. Consider the below code snippet:

var test1 = 10;
var test2;
var test3;
// test1 will still have the value as 10
var test1;

So, even after re-declaring the variable with the same name, it will persist in its previous value.

Rules for defining JavaScript Variables:

Like all the programming languages, JavaScript has also established a set of rules which govern the correct naming conventions for the variables. Few of these rules are:

  • A variable name must start with a letter, underscore(_), or a dollar sign($).
  • After the first letter/underscore/dollar, we can use numbers.
  • A variable name can't contain spaces.
  • Variables in JavaScripts are case sensitives.
  • One can't use Reserved words(e.g., abstract, final, etc.) as variables names.

Below are few of the examples which shows the categorization of a JavaScript variable as valid and invalid:

// Valid variables
var test1 = 10; // Started with letter
var  _test = “Demo”; // Started with UnderScore(_)
var $test1 = true; // Started with dollar sign($)

// Invalid variables
var 1test = 10; // Started with letter 1
var *test = “value”; // Started with special characte(*)

How to access JavaScript Variables?

As briefed in the previous chapter, JavaScript code can integrate into the HTML file using the <script> tag. The below code snippet shows how the declaration of a variable happens in a javaScript method. Additionally, it also shows how its value is accessed and printed using the document.write()  method.

<html>

   <body onload = checkVariable()>   

      <script type = "text/javascript">      

            function checkVariable( ) {

               var myVar = "ToolsQA";    

               document.write(myVar);

            }

      </script>     

   </body>

</html>

Save the file with name variables.html and open it in a browser. It should show the output as:  Variables.

As per the above code, we are creating a variable having name myVar and assigning value “ToolsQA” to that variable. Then we are just printing the value so that it appears on the browser when the user opens the HTML file in the browser.

What is the Scope of JavaScript Variables?

The scope of a variable is the part of the program which provides access to the variable. In JavaScript, there are two types of scopes:  Scope of variables in JavaScript

Let's discuss these scopes in detail.

JavaScript Variables - Local Scope:

In JavaScript, variables declared inside the function/method or block comes under the local scope. These variables have access only inside these methods/functions or blocks only.

E.g., Consider the below code-snippet, where the declaration and accessibility of the myVar variable is inside the checkVariable() method. By no means, this variable has access outside this method.

<html>
<head>

      <script type = "text/javascript">     
            function checkVariable( ) {
               // local variable only accessed inside this function
               myVar = "ToolsQA"; 
               document.write(myVar);  
            }
     </script> 

</head>

<body onload = checkVariable()>      

</body>

</html>

Save the file with name localVariables.html and open it in a browser.  Local Variable

Now consider an example, where the user tries to access, the local variable defined inside one method, in another method, as shown below:

<html>
<head>
    <script type="text/javascript">         
        function checkVariable( ) {
            // local variable declaration and initialization
            var myVar = "ToolsQA";
         }                 
        
        function clickButton(){
            // try accessing local variable in another method
            alert(myVar);
        }              
    </script>
</head>
   
<body onload=checkVariable()>          
<button onclick="clickButton()">Click me</button>
   
</body>
</html>

Save the file with name localVariablesOutOfScope.html and open it in any browser (Chrome, Firefox, or IE). Suppose we open the HTML file in the Chrome browser. Now, open the "console" of the Chrome browser by right-clicking of the browser screen and selecting inspect from the context menu. Click on the "console" tab to open the console of Chrome. Now, click on the "Click me" button. It should show the output as follows:

 Local variable out of scope

As we can see from the above screenshot that the JavaScript code has raised "Uncaught ReferenceError", mentioning that the "myVar" variable is not defined. Moreover, as the definition of the variable was in the checkVariable() method, it will not be accessible inside the clickButton() method. Now the solution to this problem is by declaring the variables in Global scope. Let's move to the next section to understand the same in detail.

JavaScript Variables - Global Scope:

In JavaScript, variables declared outside all the functions or methods come under the global scope, and any methods/functions or blocks can access them. E.g., Consider the below code snippet, the variable myVar is declared in the global scope(directly inside the <script> tag). Further, it is assigned the value inside the method checkVariable(). Finally, the same variable is being alerted in the method clickButton(), which prints the same value of the variable as it was being assigned in the checkVariable() method. So, this shows that global variables persist their values throughout the global scope, no matter where they invoke within the global scope.

<html>
<head>
    <script type="text/javascript">  
        //this is the global variable and it can be accessed in all the functions       
        var myVar;
        function checkVariable( ) {
            // Assign value to the global variable
            myVar = "ToolsQA";
         }                 
        
        function clickButton(){
            // Print value of the global variable
            alert(myVar);
        }              
    </script>
</head>
   
<body onload=checkVariable()>          
<button onclick="clickButton()">Click me</button>
   
</body>
</html>

Save the file with name globalVariables.html and open it in any browser (Chrome, Firefox, or IE). It should show the output as:  Global variable

As we can see in the above example and screenshot, the declaration of variable myVar happens outside all the functions. Moreover, it is accessible and updates inside the methods. Therefore, this makes it clear that the global variables are accessible to all the methods.

Key Takeaways

  • JavaScript supports both primitive(eg: Number, String etc.) and non-primitive(eg: Object, Arrays etc.) data types.
  • Moreover, the "var" keyword declared the variables and initialized using the equal(=) operator.
  • Additionally, the declaration of multiple variables can happen like: var test1 = “John”, test2 = “Dheer”, test3 = 200;
  • Accessibility of variables depends on whether they declare in the "local" or "global" scope.

To conclude, as we are now clear about the concepts of DataTypes and variables in JavaScript, let's move to the next article to understand the concepts of Functions in JavaScript.

How to run JavaScript Programs (with examples)?
How to run JavaScript Programs (with examples)?
Previous Article
Functions in JavaScript
Functions in JavaScript
Next Article
Arunkumar Chandra
Test USer
Reviewers
Ravinder Singh's Photo
Ravinder Singh

Similar Articles

Feedback