Understand Scope

Understand Scope in JavaScript

The scope is one of the very important and basic things of JavaScript that you need to know to understand how the function’s work.

So, what is it basically,

Scopes basically a priority order for a variable means it’s basically deciding which variables to show and which variables are not.

Types of Scope

There are many types are available in javascript, but most important types are the Local and Global scope. The other’s are Lexical and Block Scope. I’ll explain later those other’s scopes types.

Global :

When you declare a variable outside any block, then it’s called a Global Scope. Means, look at the code below,

let global;//this is a global scope

console.log(global);// undefined cause your not defining any value to that variable 'global'

global = "a value which is a string"; //now it's define.

Local :

When you create a scope locally or inside any block, then it’s called a Local Scope. Let’s look at the code below,

function newFunc(){

let local = "local variable";

console.log(local); //return "local variable"
}

newFunc();// invoke function

console.log(local); //return local is not defined

That’s how local scopes are work. but you can always call global one inside any block but if you already create a variable with the same name of the global variable inside any block, then it’s showing you the error in the console, because “you only use one particular name only one time with let” but you can always update the value but the original value remains same. Look the sample code below,

let global = "global variable";

function anotherFunc(){

console.log(global);

let global = "update the global variable value";

console.log(global);

}

anotherFunc();

in the above code, if you think the output should be “global variable” and “update the global variable” this, then buddy you’re wrong.

The output will be an Error,

global is not defined

Basically, if you use “let”, then you cannot use the same name with let statement.

But if you use “var”, which is basically no one right now but I still loved this var. The output will be,

undefined

update the global variable value

This is happening because of hoisting (another fundamental topic need to learn to understand javascript basic). I’ll write a blog about this soon. so, subscribe to get the updates.

Conclusion :

  1. first of all, decide what you should use for declaring a variable “var” or “let”. whatever you choose. don’t mix both.
  2. You can access global scopes everwhere on that page you’re writing scripts.
  3. You can access Local scopes only inside a block. After the block ends, the local scope also ends.

So, if you like this, then subscribe and get the latest update every week.

If you have any questions, doubts or suggestions about this scopes, then comment out below, i’ll reply as soon as possible.

Leave a Reply

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