Types of scope in javascript in easy way step-by-step
"Life ek Scope hi hai"

Types of scope in javascript in easy way step-by-step

ha bhai log! ab apn start krte hai drne ka nahi bhot asan hai

What is Scope in Javascript?

In JavaScript, the term "scope" refers the accessibility of a variable, function and object within a code.


Type of Scope in Javscirpt?

  • global scope // before ES6(2015)
  • functional scope // before ES6(2015)
  • block scope
  • script scope
  • local scope


Now, understand the Global scope

the scope that is accessible from anywhere in the code. Variables, functions, and objects that are declared outside of any function or block are considered to be in the global scope.

<script>
? var sohail = "Global scope";  //Global scope
</script>        

Block Scope

The variable, function are declare inside an object {} it become block scope.

NOTE: Var variable will note work in block scope!

<script>
?  if(true) {
? ? ? let mMatch = "Block scope";
? ? }
</script>        

Now, we understand what we are dicussing Sohail does everything is comes under scope in JS?

Yes, My friend everything in javscirpt is under some sort of scope.

Script Scope

This scope use to react same as Global Scope but the difference is you can't access the let and const before there intialization.

Note: only let and const comes under script scope.

Nahi ayea smjh mai ao chale code ki duniya mai :)
<script>? ? 
    console.log(a)
? ? console.log(b,c);
? ? var a = "Global Scope" // you can access the "a" before it's intialization
? ? let b = "script scope" // you will get reference error in "b"
? ? const c = "script scope";
</script>        

local scope and Functional scope

Local scope and function scope refers to the scope of a variable or function that is declared within a block statement or a function. In JavaScript, variables declared with the let and const keywords have block scope, meaning that they can only be accessed within the block in which they are declared.

<script>? 
  function theName(params) {
? ? let x = 10; // local scope
? ? console.log(x);
? ? if (params) {
? ? ? const y = 12; // block scope
? ? ? var m = 20;
? ? ? console.log(x); // outPut 10
? ? ? console.log(y); // outPut 12
? ? }
? ? console.log(m); // local scope
? ? console.log(y); // referenceError: : y is not defined
? }
? theName(true); //call the function
</script>        

Enjoy : )



Hello Mohammad... We post 100's of job opportunities for developers daily here. Candidates can talk to HRs directly. Feel free to share it with your network. Visit this link - https://jobs.hulkhire.com And start applying.. Will be happy to address your concerns, if any

回复
Fehmina Malek

BTP CSM - TOGAF certified

1 年

Nice blog Crips and to the point- one suggestion you should also write the blog on side effects of messing up with scope with examples:)

要查看或添加评论,请登录

Mohammad Sohail Khan的更多文章

社区洞察

其他会员也浏览了