DEV Community

Pawankashap
Pawankashap

Posted on

JavaScript Scope

Introduction

In this blog post, I'll explain the scope and how to use it to your advantage when writing code. I'll also look at some common scoping issues and how to solve them. Let's get started!

Types of scope

In JavaScript, scope refers to the current context of your code. This context determines where you can access certain variables and functions. In other words, where you decide to define a variable or function in JavaScript impacts where you can access it later. So, if you define a variable inside a function, you can only access it inside that function.

There are 3 types of scope in JavaScript

  • Global scope
  • Function scope
  • Block scope

Global Scope

Global scope means that a variable or function is available anywhere in your code. This is the default scope for variables and functions in JavaScript.
Let's take a look at an example:
Image description
In the code snippet above, I have defined a variable called 'animal' with a value of 'cat'. I have also defined a function called 'printAnimal', which prints the value of 'animal' to the console. Because I have defined 'animal' in the global scope, I can access it inside the 'printAnimal' function.

Function Scope

Function scope is similar to a local scope in that variables and
each function creates a new scope. However, there is one key difference: Variables defined inside a function are not accessible from outside the function.
Let's take a look at an example:
Image description
In the code snippet above, I have defined a function called 'printAnimal'. I have also defined a variable called 'animal' with a value of 'cat'.
Because I have defined 'animal' inside the 'printAnimal' function, I can only access it inside that function. If I try to access 'animal' outside of the function, I will get an error.

Local Scope

I can use let and const keywords inside the Block Scope in JavaScript. Variables declared inside a { } block cannot be accessed from outside the block
Image description
In the code snippet above, I have defined a variable called 'animal' with a value of 'dog'. I have also used the 'let' keyword to create a block scope for the variable inside the { } block.
Because I have defined 'animal' using the 'let' keyword, I can access it inside the code block. However, 'animal' is not available in the global scope. Therefore, if I try to access 'animal' outside of the code block, I will get an error.

Top comments (0)