Scope - 01

Scope: 

Scope defines where variables can be accessed or where can’t be accessed.


There are two types of scope.

  • Global scope
  • block scope.


Global scope : 

As we know that the codes inside the curly braces of function or if statement is called a block. 

If we declare a variable outside the block or curly braces of a function or an if statement, then we can access the variable from anywhere in the program. We can access this variable from the block of the code or from curly braces.











In the example above, the variable color is a Global scope because the variable has been declared outside the curly braces of function and as a result, we can access the color variable from anywhere in the program, within the curly braces also.



Block scope : 

If we declare a variable inside the block or curly braces of a function or an if statement, then we can only access this variable within this block, we cannot access it outside of the block or curly braces of a function or an if statement. This is why it is called block scope.














In the example above, the variable color is a block scope because this variable is only accessible within the curly braces or within the block, not possible to access it outside the block or curly braces.


It’s the best practice to not define variables in the global scope. A good practice is to keep variable names unique.


Post a Comment

Previous Post Next Post