Understanding scopes in Javascript- Function Scoping

Understanding scopes in Javascript- Function Scoping

The concept of scopes are in every language. A scope dictates a portion of program where a particular variable is accessible. Not all variables are accessible in every places of program. if variables are allowed access everywhere then there will be chaos. There are controlled portions in program where variables are active.

In C++ & JAVA, scopes are defined by {}, but in Javascript it’s a different case.In Javascript scoping is based on functions. Javascript has function scoping & not block scoping.

var name="Anoop";
if(name==="Anoop"){
   var surname="Rai";
}
console.log(name);
console.log(surname);

If above codes are executed both the variables(name & surname) gets printed correctly. Javascript is not block scoped, the only way to create scope in Javascript is by creating function, but there are also some new ways of creating scope in Javascript. Mostly for the most part function scoping is used.

var name="Anoop";
function getSurname(){
   if(name==="Anoop"){
      var surname="Rai";
   }
console.log(name);
getSurname();
console.log(surname);

If above codes are executed then there is error(undefined) while accessing surname variable outside the function. Function declaration has created a scope, anything that is declared(name has global scope, and surname has function scope or local scope) inside the function is available inside the function only. However, whatever is declared outside the function is available inside the function.

Leave a Reply

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