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.

Check out the video I made on the topic

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.

UPDATE (25th Feb 2018): Just wanted to point out that this writeup is slightly misleading. In this instance removing the keyword var from within the function showMsg() means that it is merely referring to the variable ‘a’ which we declared in the global scope i.e. var a on the first line.

If however, we do not declare it outside and instead declared it only inside the function without using the var keyword, that variable will be available globally. However, the variable contained within the function will not exist in the execution context until the function has been invoked at least once.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.