Blog

Filter posts by Category Or Tag of the Blog section!

JavaScript Variables

Tuesday, 30 October 2012

Variables store information so that it can be used later! Like many other programming languages, JavaScript has variables. JavaScript variables can hold a value of any data type. A variable's value can change during the script.

 

Var name;
Var age;
Var x,y,z;

 

Note: If you try to assign a value to a non-existent variable, JavaScript will create the variable for you.

You can refer to a variable by name to see its value or to change its value. The value type of a variable can change during the execution of a program and JavaScript takes care of it automatically.

Note: JavaScript variable names are case sensitive. And it's better to start with a letter or underscore "_".

 

Variable Scope

Local Variables:

For example parameters of a function is always local to the same function:

 

 function sample( name, family) {
        name = "ehsan";
        family = "ghanbari";
    }

 

local variables are available only within the section of code in which they were defined

 

Global variable:

A global variable has the global scope which means it is defined everywhere in your JavaScript code. Take a look at this example:

 

var culture = "something";                       
function sample( ) {
   base.culture = "base culture";                          
   return null;
}

function sample2() {
   var localVar="this culture";                    
   return null;

}

 

Definitely, the variable in the sample is global (because of base) and the one in sample2 is local.

 

Read more:

  1. http://www.tutorialspoint.com/javascript/javascript_variables.htm
  2. http://webcheatsheet.com/javascript/variables.php

Category: Software

comments powered by Disqus