Jump to content

Distinction between local and global variables - JavaScript

0
  Ángel Manuel García Carmona's Photo
Posted Sep 09 2010 09:45 AM

Variables are containers that store data structures that are used by a program. When driving variables and functions, we must distinguish between two types of variables:

  • LOCAL - Are those that are specific to a function and only work on it.
  • GLOBAL - Are those that are not defined within a function and may also serve to functions unless the function has not required that variable.

The following blocks corresponds to a local variable and a global variable respectively:

var mensaje = 'Outside the función';
function aviso() {
var mensaje = 'Inside the función';
alert(mensaje); //'Inside de la función'
}
aviso();
alert(mensaje);//'Outside the función'

var mensaje = 'Outside the función';
function aviso() {
alert(mensaje); //'Outside the función'
}
aviso();
alert(mensaje);//'Outside the función'

In the second block, having no function variable itself, it displays the same message both inside and outside the function.
There are exceptional cases in respect to global variables and cases in which those inside the function if we add one line of code like this "message = 'Inside function'" (message is the name of the variable, but is not accompanied by "var" to not be a new variable, but a new one is stored within the same, consisting of the line in "variableName = 'Message'") and having it programmed, the messages after the first issue of that line as being of programmed that way as well:

var mensaje = 'Outside the función';
function aviso() {
mensaje = 'Inside the función'
alert(mensaje); //'Inside the función'
}
aviso();
alert(mensaje);//'Inside the función'

Ángel Manuel

Tags:
0 Subscribe


1 Reply

0
  AlejandroLechuga's Photo
Posted Sep 10 2010 11:19 AM

I'll bookmark this, thanks.. I did this post ttp://blog.ramonlechuga.com/2010/08/12/private-public-properties-for-javascript/