JavaScript Variables – A to Z Guide for a Newbie in JavaScript!

Variable means anything that can vary and holds the data value and we can change it anytime. A variable must have a unique name. Variables in JavaScript are tanks which keeps a hold on metamorphic data. Today in this tutorial, we will learn about variables in JavaScript. We will try to understand when and how to use them. We will also take a brief look at how JavaScript variables work and the basic points you need to remember while applying them, rules associated with variables, identifiers, and keywords.

Before starting with this blog, we recommend you to gain a thorough understanding of JavaScript Operators

So, let’s get started with what JavaScript variables actually are.

Keeping you updated with latest technology trends, Join DataFlair on Telegram

What are JavaScript Variables?

The word ‘variable’ means anything that can vary. Thus, the data values stored in a JavaScript variable can be changed anytime. Every programming language, be it C/C++ or Java, uses variables. We can use variables as symbolic names for values in an application.

Suppose you are shopping in a mall for some of your favorite items. You have a cart to put the items you want to buy in; this is your variable. You named it “yourCart”; this name you provided is an Identifier. You select and store everything you want in yourCart. Anything you put inside yourCart is your data. You can add or remove your data anytime you wish.

This is similar to how we deal with variables in JavaScript. JavaScript variables can store any data values (e.g., a number, a string, etc.).

Hello message cart - JavaScript Variables

A variable can be created using any of the three keywords: ‘var’, ‘let’ and ‘const’. You don’t need to worry if many of these words are new to you. You will understand these terms as you proceed further in this article.

Variables Scope in JavaScript

The region of your program where you define your variable is the variable’s scope, or you can say that the lifetime of a variable is its scope. There are three types of JavaScript variables:

  • Global variables: They have global scope i.e. they can be defined anywhere in your JavaScript code.
  • Local variables: These are only visible in the function in which we define them. They will not have any significance outside that function.
  • Block variables: They have block scope i.e., they are defined inside a block { }, not necessarily a function. These are added in the program with the help of ‘let’ and ‘const’ keywords (new in EcmaScript 2015).

Difference between Global and Local Variables

ParameterGlobalLocal
DeclarationDeclared outside the function.Declared inside the function.
ScopeThroughout the program.
Within the function inside which we declared them.
ValueIf not initialized, it stores zero as a default value.
If not initialized, it stores a garbage value.
LifetimeCreated before program execution and lost when the program terminates.
Created when the function executes and lost when the function terminates.
Data SharingPossible; multiple functions can access the same global variable.
Not possible; only a single function can access the local variable.
StorageStored in a fixed location decided by the compiler.
Stored on the stack, unless specified otherwise.

Before using global variables in your program, you must understand that it isn’t always a good idea to declare a global variable. You should be very careful where you use them because of the following reasons:

  • It is hard to know which function is using them.
  • It requires larger memory space as compared to local variables.
  • Multiple functions using the same variable will reduce the speed of the program.
  • It sometimes becomes unreliable; debugging is difficult.
  • It reduces the flexibility of your program since you will have to change many things to edit even a single thing.

Time to revise the JavaScript Syntax and Implementation

Variable Declaration in JavaScript

As mentioned earlier, JavaScript uses keywords; var, let and const to declare a new variable. Let’s explore them all in more detail:

1. Using var

With the help of a var statement, we declare a variable, optionally initializing it to a value. We can reassign the values to the variables or redefine the variables. If you re-declare a variable, it will not lose its value. The syntax for this declaration is as follows:

var varName; //without initializing
var varName = “DataFlair”; //initialized with a string

Multiple variables can be declared in a single line, separating them with commas.

var var1 = 12, var2 = “DataFlair”,...;

Code:

<html>
  <body>

    <script>
      var var1 = "DF";
                        document.write("Variable's value is " + var1);
                        document.write("</br>After redeclaration,</br>");
                        var var1 = "DataFlair";
                        document.write("Variable's value is " + var1);
    </script>

  </body>
</html>

Screenshot:

using var

Output:

using var op

In JavaScript, all the declarations (including variable declarations) are processed before program execution. Thus, declaring a variable anywhere is equivalent to declaring it at the top of the code. This provides JavaScript with the functionality to use the variables before their declarations in the code. We call this behavior of variables “var hoisting”.

But it is always recommended in programming to declare the variables before using them. This will help you avoid unintentional redeclaration of a variable.

This variable declaration method is rarely used by programmers, and you too need to consider either let or const for your variables.

2. Using let

These are declared in a similar manner to var declared variables. But we use the let keyword instead of var; this has scope constraints. You cannot redeclare the let declared variables. You will face a SyntaxError if you try to do so. The scope of these variables is the block they are defined in, as well as any sub-blocks. The browser will throw a ReferenceError if you try to access these variables outside of their block.

let varName1; //without initializing
let varName1 = “DataFlair” // initialized with a string

Code:

<html>
  <body>

    <script>
      {
        let variable; //variable declaration
      document.write(variable + "</br>"); //accessed inside the block
      }
      document.write(variable + "</br>"); //cannot 
                        access outside the block
                        let var2 = "DF"; //variable declaration and initialization
                        document.write("Variable's value is " + var1);
                        document.write("</br>After redeclaration,</br>");
                        //let var2 = "DataFlair"; //variable redeclared
                       //document.write("Variable's value is " + var1); //Uncaught SyntaxError
    </script>

  </body>
</html>

Screenshot:

using let1

Output:

using let1 op

We experimented with ReferenceError. Let’s declare the initial statements as comments and remove the comments from the last two statements.

Code:

<html>
  <body>

    <script>
    {
        let variable; //variable declaration
      document.write(variable + "</br>"); //accessed inside the block
      }
                        //document.write(variable + "</br>"); //cannot access outside the block
                        let var2 = "DF"; //variable declaration and initialization
                        document.write("Variable's value is " + var1);
                        document.write("</br>After redeclaration,</br>");
                        let var2 = "DataFlair"; //variable redeclared
                        document.write("Variable's value is " + var1); //Uncaught SyntaxError
    </script>

  </body>
</html>

Screenshot:

using let2 - JavaScript Variables

Output:

using let2 op - JavaScript Variables

3. Using const

Much like variables defined using the let statement, constants are block-scoped. The const declaration creates a constant whose scope can be either global or local to the declared block in which we declare it. The value of a constant is read-only; you cannot change it through reassignment, and you can’t redeclare it. An initializer for a constant is required; i.e., you must specify its value in the same statement in which it’s declared (since you can’t alter it later). A function or a variable in the same scope cannot have the same name as the variable.

It is a good practice to declare your constants in uppercase. This will help programmers differentiate the constants from other variables in the program.

const VARNAME = “DataFlair”; // initialized with a string

Code:

<html>
  <body>

    <script>
      {
        const VARIABLE; //SyntaxError
        document.write(VARIABLE + "</br>"); //accessed inside the block
      }
                        /*const VAR3 = "DF"; //variable declaration and initialization
                        document.write("Variable's value is " + VAR3);
                        document.write("</br>After redeclaration,</br>");
                        VAR3 = "DataFlair"; //variable redeclared
                        document.write("Variable's value is " + VAR3);*/
    </script>

  </body>
</html>

Screenshot:

using const1 -JavaScript Variables

Output:

using const op - JavaScript Variables

Let’s alter our code a bit. Comment the first block and remove comments from the other statements.

Code:

<html>
  <body>

    <script>
      /*{
        const VARIABLE; //SyntaxError
        document.write(VARIABLE + "</br>"); //accessed inside the block
      }*/
      const VAR3 = "DF"; //variable declaration and initialization
      document.write("Variable's value is " + VAR3);
                        document.write("</br>After redeclaration,</br>");
                        VAR3 = "DataFlair"; //variable redeclared
                        document.write("Variable's value is " + VAR3);
    </script>

  </body>
</html>

Screenshot:

using const2

Output:

using const1 op - JavaScript Variables

Did you explore the article on JavaScript Functions?

Naming Variables in JavaScript

Variable names in JavaScript are often known as identifiers. Identifiers are a sequence of characters in a program that identifies a variable, function, or property. These are the names we use in JavaScript as a name to declare any variable.

The rules for naming a variable includes:

  • The first character must be a letter, a dollar sign ($) or an underscore (_).
  • The rest of the variable name may contain any letter, number, dollar ($) or an underscore (_).
  • Spaces and special symbols (like @ ! # etc.) are not allowed as part of variable names.
  • You must not use JavaScript’s reserved words as variable names.
  • There is no limit for the length of the variable name.

Points to Remember

JavaScript doesn’t throw an error for a variable name that satisfies the above conditions. But this does not mean that you use any identifier you want. For creating simple, easy-to-interpret, easy-to-debug and efficient programs, you must assign meaningful names to your variables. Some points you need to remember while naming a variable are as follows:

  • Make sure you provide descriptive names for your variables. Using names with a few characters is easy to type. But these are only useful in small programs. When you are working on a larger project, you eventually forget the names you initially assigned.
  • Since JavaScript is case-sensitive, variable and Variable are two different identifiers. But you should not use them both in your program. Your program will be more error-prone if you do so.
  • Try to make your variable names as different from the keywords and other built-in terms as you can to avoid confusion.
  • The best way to create a variable is to use multiple words. JavaScript programmers prefer Camel Case for their variable names (e.g., myVarName). Except for the first character of the name, all the first words are uppercase and others are lowercase.
  • You should avoid creating extremely long variable names. This will take longer to type and are more susceptible to errors.

JavaScript Reserved Words

JavaScript has some words reserved for itself. When you try to use them in your program as your variable names, JavaScript gets defensive. It’s like, “Woah! I’m using that word, so you’re not allowed to use it. You get yourself another variable name.”
These reserved words are famous by the name “keywords”. Keywords are just some special words, that JavaScript uses to function. You cannot choose these words as identifiers.

The following table lists the various EcmaScript 2015 Reserved Words in JavaScript:

breakcasecatchclass
constcontinuedebuggerdefault
deletedoelseexport
extendsfinallyforfunction
ifimportininstanceof
newreturnsuperswitch
thisthrowtrytypeof
varvoidwhilewith
yield

Future Reserved Keywords

These keywords do not have any special functionality at present, but they might. Hence, we cannot use them as identifiers.
enum is always reserved.

As listed in the following table, other keywords available in the older standards (EcmaScript 1 to 3) are:

abstractbooleanbytechar
doublefinalfloatgoto
intlongnativeshort
synchronizedthrowstransientvolatile

You also cannot use other literals null, true and false as identifiers in EcmaScript.

Summary

Here we come to the end of our tutorial on JavaScript Variables. In this article, we went through variables and constants. We took a brief look at different types of variable, different methods to declare them, and rules for identifiers and the best practices to decide on them. And last but not least we also learned about JavaScript Keywords.

Thinking, what next? Here is the article on JavaScript Data Types for you

Hope the information provided was useful to you.

Don’t forget to drop your feedback below in the comment section.

1 Response

  1. Adnan Rifat says:

    The class was very effecttive to me …………….thanks for your support

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.