Scope in JavaScript

What is Scope?

Scope determines the accessibility of variables. Each function when invoked creates a new scope. In JavaScript there are two types of scopes:
1. Global Scope
2. Local Scope

Global scope: variables defined outside of a function or curly braces {} are in the global scope. Once you’ve declared a global variable, you can use that variable anywhere in your code.

Local Scope: variables defined inside of a function or curly braces {} are in the local scope. Once you’ve declared a local variable, these are usable only in a specific part of your code.

Note: You can use the same name of local variables in different functions. Every time when you call the function they have a different scope. So the same name can’t affect each other.

In JavaScript, there are two kinds of local scope.

  1. Function scope
  2. block scope.

Function scope: When you declare a variable inside a function, you can access this variable only within the function.

Block scope: When you declare a variable within a curly brace {}, you can access this variable only within that curly brace.

Problem Start with var keyword in block scope:

Here you can see that, even though the variable cat is in a block scope, but it still accesses it in another block. You Can fix this problem using the ‘let and const’ keyword.

Difference Between var, let, and const:

I hope this lesson provides a clear understands of how scope works in JavaScript. Hopefully, you learned something today. Happy Coding.




Web Developer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Feathers-Plus CLI

Approaching Algorithms with JavaScript

Pandas read_excel removed support for xlsx files

10 Important JavaScript Concepts

Beta Testing React Native Android Applications with Crashlytics

How to make interactive components in Storybook (ReactJS) with ‘controls’ module the fast way

Node-Express-Typescript Services as AWS Lambda function with AWS DynamoDB and DynamoDB Local

Which apollo-server to use? Comparing apollo-server, apollo-server-express, apollo-server-*

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Abdullah Imran

Abdullah Imran

Web Developer

More from Medium

JavaScript declarations var, let, const

Eloquent Exercises: Groups | Eloquent Javascript, Chapter 6

All JavaScript array methods

JavaScript Coding Tutorial — Part 1

Have fun playing with different numbers and colors, and let your JavaScript app run for a while.