Programming Language

When Should You Use the “var” Keyword in JavaScript?

“Var” is the keyword for variable in JavaScript. It is used to declare, name and represent data in JavaScript. The use of variables in JavaScript is to manipulate the variables in terms of values/names during code’s runtime. You must try to assign meaningful names/values for proper execution of codes. The keyword “var” is used in a variable statement written before enclosing a function.


Before starting a script, you have to declare the variables. They are saved in the memory. It allows you to look up and use the declared variable later or at the end of the script. You can use declare your referring variables by using the keyword “var”. In case you forget to mention a value for the variable in declaration, JavaScript takes it as an unidentified one. Here is an example:


// A single declaration.

var count;

// Multiple declarations with a single var keyword.

var count, amount, level;

// Variable declaration and initialization in one statement.

var count = 0, amount = 100;



The only case-sensitive language in computer world is JavaScript. From this it is obvious that variable name that is in capital letters differs from the one in lowercase letters. You can name the variables if they fall under the legal rules of naming, although there is no restriction on its length. During naming “var” can also be used in the following ways:

  • In an expression where you have to declare and initialize a variable but at the same time do not have to assign it any specific value other than null you can use “var”. Here it is given below:



var bestAge = null;

var muchTooOld = 3 * bestAge; // muchTooOld has the value 0.



  • When you have to declare and name an undefined variable i.e. a variable without a designated value, you can use “var” as follows:




var currentCount;

// finalCount has the value NaN because currentCount is undefined.

var finalCount = 1 * currentCount;

Leave a Reply