cover-img

Scoping in JavaScript

Scoping - Definition, Type , Lifetime

1 November, 2022

0

0

0

Contributors

Scope refers to the availability/accessibility of variables.
For illustrating , suppose we have two scopes thar are given below.
In general, if a variable defined inside your scope , you can’t access it outside their scope. But your scope can access elements defined outside of it i.e in their scope
Mainly 3 types of scopes exists in JavaScript:

Block Scope

Function Scope

Global Scope

Block Scope

Above example will throw an error

You can access outside scope element from inside scope but reverse is not true.

But if we use var keyword to create that scope than above example will not throw any error

Local Scope

If we use declare a variable inside a function in JavaScript , then the variable created has a local scope. Also any parameters defined in function protoype are also Local.

Function Scope:

Variables declared inside a function are not accessible from outside the function.

Global Scope:

Variables created in this scope can be accessed anywhere inside the script.
Do it yourself with var & const global variables and try to access them inside the function.
If you don’t declare variable with any keyword(const,let,var) but initialize them with a value, they will be automatically declared as a global variable.
But in case of functions you also need to call the function to make it work
All modern browsers support running JavaScript in Strict Mode. So I will not suggest you to use undecalred variables, otherwise you have to debug.
But I highly suggest you to not use any global variable. Because anyone can change its values and it will be harder for us to debug.

The lifetime of a JavaScript variable starts when it is declared.

Function (local) variables are deleted when the function is completed.

In a web browser, global variables are deleted when you close the browser window (or tab).

Comment if I have committed any mistake. Let's connect on my socials. I am always open for new opportunities , if I am free :P

0

0

0

Saurav

Haryana, India

Looking for Full Stack Development Opportunity | MERN, React Native, Kotlin, C++

More Articles

Showwcase is a professional tech network with over 0 users from over 150 countries. We assist tech professionals in showcasing their unique skills through dedicated profiles and connect them with top global companies for career opportunities.

© Copyright 2025. Showcase Creators Inc. All rights reserved.