Variable Scope

One more thing you should be aware of is if you create a function and defined a variable inside that function, that variable only available inside that function. It is because something called variable scope, where is that variable is visible. For example :

function simpleFunction() {
    var x = 50;
    alert(x);
}

You declared a variable x inside a function, so you can alert it no problem. But, when you write like this :

function simpleFunction() {
    var x = 50;
}

simpleFunction()
alert(x);

It will cause error because variable x is not visible outside the function. You can write a global variable to prevent this ever happen. Global variable is variable that you write usually at the beginning of the code so it can be used anywhere, inside or outside function.

var x;   //global variable

function simpleFunction() {
    x = 50;
}

simpleFunction()
alert(x);

results matching ""

    No results matching ""