search
HomeWeb Front-endJS TutorialDetailed explanation of the difference between scope and block-level scope in Javascript

Scope is always the top priority in any programming language, because it controls the visibility and life cycle of variables and parameters. Let me introduce to you the scope and block-level scope in Javascript. Friends who need it can refer to it

1. Description of block-level scope

Before learning the variable scope of JavaScript, we should clarify a few points:

a. The variable scope of JavaScript is based on its unique scope chain.

b. JavaScript does not have block-level scope.

c. The variables declared in the function are defined throughout the function.

The variable scope of javascript is different from the C-like language commonly used. For example, the code in C#:

static void Main(string[] args)
{
   if(true)
   {
    int number=10;
   }
  Console.WriteLine(number);
}

This code cannot be compiled because "the current context does not Number".

exists because the scope of the variable here is limited by curly braces, which is called block-level scope.

In the block-level scope, all variables are within the defined curly braces. They can be used in the range from the beginning of the definition to the end of the curly braces. They cannot be accessed outside this range, that is to say

if(true)
{
  int number=10;
  Console.WriteLine(number);
}

This can be accessed because the definition and use of variables are within the same curly braces.

But there is no concept of block-level scope in JavaScript.

2. Scope in javascript

1. Function limited variable scope

In javascript, inside the function The defined variables can be accessed inside the function, but cannot be accessed outside the function. Code:

<script type="text/javascript">
  var num=function()
  {
   var number=10;
  };
  try{
    alert(number);
  }catch(e)
  {
    alert(e);
  } 
</script>

When the code is run, an exception will be thrown. The variable number is not defined because it is defined in the function. Variables cannot be used outside the function, but can be used arbitrarily within the function, even before assignment:

<script type="text/javascript">
 var num=function(){
    alert(number);
    var number=10;
    alert(number);
 };
 try{
   num();
 }catch(e){
  alert(e);
 }
</script>

After this code is run, no error will be thrown, and it will pop up twice, namely undefined and 10

2. Subdomain accesses parent domain

The function can limit the scope of the variable, then the function in the function is the subdomain of the scope, and the function in the subdomain The code can access the variables in the parent domain. The code is as follows:

<script type="text/javascript">
 var func=function(){
    var number=10;
    var sub_func=function(){
      alert(num);
    };
   sub_func();
};
func();
</script>

The result of executing this code is 10, but accessing the code of the parent domain in the child domain is also conditional

<script type="text/javascript">
 var func=function(){
    var number=10;
    var sub_func=function(){
      var num=20;
      alert(num);
    };
   sub_func();
};
func();
</script>

This code has one more "var num=20;" than the previous one. This code is in the subdomain, so the situation of the subdomain accessing the parent domain has changed. The result printed by this code is 20. At this time, the subdomain The num accessed by the domain is a variable in the child domain, not the parent domain. It can be seen that there are certain rules for access. When using variables in JavaScript, the JavaScript interpreter first searches whether there is a definition of the variable in the current scope. If there is, this variable is used. If not, it goes to the parent domain to find the variable. , and so on, until the top-level scope is still not found, an exception "variable is not defined" will be thrown. The code is as follows:

<script type="text/javascript">
 (function (){
   var num=10;
   (function (){
     var num=20;
     (function(){
     alert(num);
      })();
   })();
  })();
</script>

After this code is executed, 20 will be printed. If "var num is =20" is removed, then the printed value is 10. Also remove "var num=10", then an undefined error will occur.

The following is an introduction to JS scope and block-level scope

Scope is always the most important thing in any programming language. Heavy because it controls the visibility and life cycle of variables and parameters. Speaking of which, first understand two concepts: block-level scope and function scope.

What is block-level scope?

Any set of statements in a pair of curly braces ({ and }) belongs to a block. All variables defined in it are invisible outside the code block. We It's called block scope.

The function scope is easy to understand (*^__^*). The parameters and variables defined in the function are not visible outside the function.

Most C-like languages ​​have block-level scope, but JS does not. Please see the following demo:

//C语言 
#include <stdio.h> 
void main() 
{ 
  int i=2; 
  i--; 
  if(i) 
  { 
    int j=3; 
  } 
  printf("%d/n",j); 
}

When you run this code, the error "use an undefined variable:j" will appear. As you can see, the C language has block-level scope because j is defined in the if statement block, so it is inaccessible outside the block.

How does JS behave? Let’s look at another demo:

functin test(){ 
 for(var i=0;i<3;i++){   
 } 
 alert(i); 
} 
test();

When you run this code, "3" pops up. It can be seen that outside the block, the variable i defined in the block is still is accessible. In other words, JS does not support block-level scope, it only supports function scope, and variables defined anywhere in a function are visible anywhere in the function.

So how do we make JS have block-level scope? Do you still remember that variables defined in a function will be destroyed when the function is called? Can we use this feature to simulate the block-level scope of JS? Take a look at this DEMO:

  function test(){ 
 (function (){ 
 for(var i=0;i<4;i++){ 
 } 
 })(); 
 alert(i); 
} 
test();

这时候再次运行,会弹出"i"未定义的错误,哈哈,实现了吧~~~这里,我们把for语句块放到了一个闭包之中,然后调用这个函数,当函数调用完毕,变量i自动销毁,因此,我们在块外便无法访问了。 

JS的闭包特性is the most important feature((*^__^*) 大家懂的)。在JS中,为了防止命名冲突,我们应该尽量避免使用全局变量和全局函数。那么,该如何避免呢?不错,正如上文demo所示,我们可以把要定义的所有内容放入到一个

(function (){ 
//内容 
})();

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

使用nginx + node如何部署https

在JavaScript中如何实现AOP

在mongoose中有关于更新对象的详细介绍

在JS函数中有关setTimeout详细介绍

使用jquery如何实现侧边栏左右伸缩效果

在Vue中如何实现数字输入框组件

The above is the detailed content of Detailed explanation of the difference between scope and block-level scope in Javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment