Scope in JavaScript

JavaScript implicitly types variables, i.e. you don’t have to do it yourself. Similarly there’s no access modifiers used, bar one. This ‘access modifier’ – the var keyword – isn’t intuitive in the least.

Does it imply that something is a variable? And the fact that variables can be created without it leaves people thinking its usage is stylistic. However var’s purpose is very different and unlike languages that are strongly typed or Python which actually uses an intuitive keyword in its stead – global – var is somewhat ambiguous if used at all.

Its function is to somewhat identify whether a given variable is local or global in scope. To further add to the confusion, anything that is declared in a JavaScript file will be considered global in scope, outside of functions and closures that is.

Function variables

Variables within a function are scoped to that function only. This includes parameters. For the sake of this explanation let’s just focus on variables within function bodies.

var a = "outside function scope";
var b = "still outside function scope";

function showMsg(){
    var a = "inside function scope";

showMsg();  // displays -> "still outside of function scope" 
alert(a);   // displays -> " "outside function scope"

in the preceding example, the alert method will show the value of the global var a which is declared at the top of the code. The var a delcaration within the function ‘showMsg()’ is not accessible outside the function.

By changing the scope of variable ‘a’ within the function by removing the keyword ‘var’ however, its scope is changed to global and this will overwrite the variable a in the global scope. The alert(a) call will return with the assignment inside the function call, namely the message, “inside function scope.”

function showMsg(){
    a = "inside function scope";

This may appear that it’s referring to the variable within the function, however that scope ceases to exist once the function call returns.