Javascript Tutorial: Variable Scope and The Var Keyword: Simple Example With Comments
Javascript Tutorial: Variable Scope and The Var Keyword: Simple Example With Comments
keyword
Global means a variable can be referenced anywhere in the current document. Local
means a variable can only be referenced within the function it is declared.
You can reference all local variables inside the same function the variables are
declared.
(L1) local variable declared with var keyword
(L2) local variable declared without var keyword
(L3) local variable declared with var keyword inside if statement
Outside a function, you can only reference local variables that are not declared with
the var keyword.
Commented out. Cannot reference (L1)
(L2) local variable declared without var keyword
Commented out. Cannot reference (L3)
Note that this JavaScript is placed between the <body> tags, not in the <head>.
function sampleFunction()
{
var localVar1 = '(L1) local variable declared with var keyword';
localVar2 = '(L2) local variable declared without var keyword';
if (someBoolean) {
var localVar3 = '(L3) local variable declared with var
keyword inside if statement';
}
sampleFunction();