More on JavaScript variables

This page is marked as In Progress so expect small errors or unfinished bits

You learned about JavaScript variables in the Beginners' JavaScript section. There is more to learn.

Global and local variables

Imagine this:

var thisVariable='';
someFunction(){
    var someVariable=1;    
}
otherFunction(){
    var otherVariable='fred';        
}
        

The variable thisVariable will be available anywhere in the script as it is declared outside of the functions. This means that both functions (or any code not in a function) can access that variable or change it.

In contrast someVariable cannot be accessed by the code in otherFunction() or any code outside of the two functions.

Global variables (like thisVariable) are available throughout the SCRIPT code. Local variables (the other two) are available only in the function where they are declared.

Global variables might seem easier but it is safer to use local variables and pass the variables between functions most of the time.

Clearing a variable

If a variable has been declared but no value has been assigned to it then it will show as "undefined":

var fred;
alert(fred);
        

Try that if you haven't come across it by accident already. You learned about IF statements in the introductory JavaScript section. One useful question is "Is the variable defined yet?":

if (fred==undefined) alert('help!');            
        

If you use a variable but then want to clear it many people will do that this way:

fred='';            
        

However, the variable fred is now empty rather than undefined. This would be better:

fred=undefined;            
        

Now that IF statement will work both before the variable is ever used and after it has been used then cleared again.

submit to reddit Delicious Tweet