Declaring and Naming JavaScript Variables

Variable are used as a container, where we can put different types of value into this container, and then we can use or manipulate this value, also replace the container with a new content. Many other programming languages support variables, JavaScript also support variables. But the variable declaration process are different. In JavaScript variable are declare with “var” keyword and after that give the variable name and then give the variable value. I am showing the example below:


var variable_name = “value”;

var address = “new town”;


(We need to keep the name unique for this variable)


When we declared variable in the JavaScript then we need unique name to this variable. And value must follow the rule below.

Variable value for string = “value will be within double or single quotation.”

Variable value for number or integer = value will be without double or single quotation.


Note: If variable is declared with the same name in a script and when it is call, the value will be immediate above variable.



There are two type/scope of variable in javascript


  • Global variable – a global variable has global facilities that means global variables defined in the entire script.
  • Local variable – a local variable only useable in the functions where is defined.

Here an example of local and global variables:




<html lang="en-US">


          <meta charset="UTF-8">


          <script type="text/javascript">

                   var glbl_var = "This is global variable";

                   var lcl_var = "This is now global variable";




          <script type="text/javascript">

                   function showVar()         {

                             var lcl_var = "This is local variable";

                             document.write(glbl_var + "<br />" + lcl_var);


                   document.write(glbl_var + "<br />" + lcl_var);





There are some example/ rule of variable naming and declaring process:



Var name _one; // we declare a variable but do not assign any value, so the variable value is undefined;

Var name _two = 12.24; // this variable contains primitive data type with number value;

Var name _three = “test”; // this variable contains primitive data type with string value;

Var name _four = “123 test”; // this variable contains primitive data type with mix of number and string value;

Var name _five = 123 + “test”; // this variable contains primitive data type with numeric and string, creating a string variable;

Var name _six = (1>2); // this variable is a Boolean value;

Var name_seven = name _six; // this variable is assign with another variable;