Learning JavaScript tutorial – JavaScript Variables
JavaScript Variables are the main building blocks of JavaScript Scripting language. JavaScript Variables are used for storing (contains) the data (value) and manipulate that data in your programs.
Every JavaScript variable has a name, called its ‘identifier’ and optional data called ‘Literals’. JavaScript Variables are declared using JavaScript ‘var’ keyword. JavaScript var keyword allocates storage space for variable to store data. Multiple variables can be declared with one JavaScript ‘var’ keyword. The main advantage of JavaScript variable is, it can hold a value of any data type. Using an undeclared variable causes an error. The best practice of defining JavaScript Variables is with assigned initial values.
var intNum; //variable intNum is declared
var intNum=10; //variable declared with assigned initial values
var x=5, y=4, z=x+y; //multiple variables with one var keyword
JavaScript Variable Scope
The scope of a JavaScript variable is limit to the block of JavaScript code in which it is defined. They are local variables to that block of JavaScript code and have local scope. JavaScript variables declared within a function, class or conditional loop are local only within the body of the function, class or conditional loop. A global variable has global scope; it is available everywhere in your JavaScript code.
var varGlobal = "I love JavaScript"; // Declare a global variable
function varScope( ) {
var varGlobal = "I love .Net"; // local variable with the same name
document.write(varGlobal); // print – I love .Net
varGlobal ="I love C#" //local scope
}
varScope( );
document.write(varGlobal); // print – I love JavaScript
JavaScript Variable Naming Conventions And Good Programming Practice
- JavaScript is a case-sensitive language so take care while defining and using variables names.
- Do not use reserverd keywords as variables names.
- Variable names must begin with a letter or the underscore character followed by subsequent characters can be a letter, a digit, an underscore.
- JavaScript variable names may not start with a numeral (0-9).
- JavaScript variable names should be more descriptive of what data the variable holds.
- The best practice of defining JavaScript Variables is with assigned initial values.





[...] JavaScript allows us to assigned any variable with any value. This feature of javascript provides great flexibility in coding. In this article we are going to Understand the JavaScript Variable Types. If you want to learn some basic about the JavaScript Variables please go through "Learning JavaScript tutorial – JavaScript Variables". [...]