search
HomeWeb Front-endFront-end Q&AWhat is the difference between es5 and es6 scopes

Difference: There are only two types of scope in es5: global scope and function scope, while there are three types of scope in es6: global scope, function scope and block-level scope, with a new one added Block-level scope. The role of block-level scope: It can solve the problem of outer variables being overwritten due to the promotion of inner scope variables, and prevent variables used for loop counting from leaking into global variables.

What is the difference between es5 and es6 scopes

The operating environment of this tutorial: windows7 system, ECMAScript version 6, Dell G3 computer

The scope of es5 and es6 Difference:

  • There are only two scopes in es5: global scope and function scope

  • Scope in es6 There are three types: global scope, function scope and block-level scope

In Es5, there are only global scope and function scope

ES5 Use var to declare variables. Variables declared with var may exist in the global scope or in the local scope. The specific situation is as follows

1. Global scope

Three situations of having global scope

a. Variables declared outside the function have global scope
b. Undefined variables with direct assignment automatically Declared as a global variable
c. The properties of the window object have global scope

2. Local scope (function scope)

The scope of variables in the function body

  • Variables defined within the function can only be accessed within the function

Example

  var a = 1;
  console.log(a);// 1                  此处a为全局变量,在全局作用域下都可访问得到

  b = 2
  console.log(b); // 2                 此处b未被var定义,而是被直接赋值,自动声明为全局变量
  
  function fun() {
    var c = 3;
    console.log(c);//3                 此处c存在在函数作用域中,仅在函数fun中可访问
  }
  fun()
  console.log(c);// undefined         全局作用域下访问函数作用域中的变量c,得到undefined

New block-level scope in Es6

Block-level scope can be simply understood as: the content enclosed in curly brackets {}, it can Contains a scope of its own. Variables in block-level scope are declared by let and const

Why is block-level scope needed?

1. Solve the problem of outer variables being overwritten due to promotion of inner scope variables

var i = 5;
function fun(){
  console.log(i);//undefined
  if(true){
    var i = 6
    console.log(i);//6
  }
}
fun()

Execution results
What is the difference between es5 and es6 scopes
The variable i in function fun is declared using var. This involves the issue of variable promotion. The so-called variable promotion means that function declarations and variable declarations are always quietly "promoted" to the top of the method body by the interpreter. So the i here is equivalent to reaching the top of function fun in advance, but the assignment is still performed when i = 6 is running. The above code is actually equivalent to:

var i = 5;
function fun(){
  var i;
  console.log(i);
  if(true){
    i = 6
    console.log(i)
  }
}
fun()

When the first i is printed , i is only declared but not assigned (i is assigned a value of 6 in the if statement), so the first printed i is undefined, and the second printed i is 6

var i = 5;
function fun(){
  console.log(i);//5
  if(true){
    let i = 6
    console.log(i);//6
  }
}
fun()

If used let declares the variable i in if, then the curly braces { } where the if statement is located will form a block-level scope, and the variables declared in this scope will be "bound" in this area and will no longer be affected by the outside. (i.e. temporary dead zone), so the first i output when executing the fun function is var i=5 in the global scope, and the i output in the if statement is let i=6## declared in the block-level scope.

#2. Prevent variables used for loop counting from leaking into global variables

for(var i = 0; i < 3; i++){
  doSomething()
}
console.log(i)//3

The above code declares the i variable with var for loops. Ideally, i should only be used in loops. It is valid in the body, but i here is exposed in the global scope, so after the loop ends, the value of i can still be accessed in the global scope

for(let i = 0; i < 3; i++){
  console.log(i)
}
console.log(i)//undefined

If you use block-level scope let to declare i, then the i variable declared here is only valid within the for loop curly braces { }. Accessing variables in the block-level scope in the global scope will result in undefined

Block-level scope features

1. Variables declared by let are only valid in the scope (within the current curly braces), so arbitrary nesting is allowed, at each level They are all separate scopes

2. The inner scope can have the same name as the outer scope variable (no scopes are used without interfering with each other)

3. let can only exist in the current scope Top level

Note: If there are variables/constants declared by let or const in { } in if statements and for statements, the scope of the { } also belongs to the block scope

Examples about scope

<script type="text/javascript">
	{
		var a = 1;
		console.log(a); // 1
	}
	console.log(a); // 1
	// 可见,通过var定义的变量可以跨块作用域访问到。

	(function A() {
		var b = 2;
		console.log(b); // 2
	})();
	// console.log(b); // 报错,
	// 可见,通过var定义的变量不能跨函数作用域访问到

	if(true) {
		var c = 3;
	}
	console.log(c); // 3
	for(var i = 0; i < 4; i++) {
		var d = 5;
	};
	console.log(i);	// 4   (循环结束i已经是4,所以此处i为4)
	console.log(d); // 5
	// if语句和for语句中用var定义的变量可以在外面访问到,
	// 可见,if语句和for语句属于块作用域,不属于函数作用域。

	{
		var a = 1;
		let b = 2;
		const c = 3;	
		
		{
			console.log(a);		// 1	子作用域可以访问到父作用域的变量
			console.log(b);		// 2	子作用域可以访问到父作用域的变量
			console.log(c);		// 3	子作用域可以访问到父作用域的变量

			var aa = 11;
			let bb = 22;
			const cc = 33;
		}
		
		console.log(aa);	// 11	// 可以跨块访问到子 块作用域 的变量
		// console.log(bb);	// 报错	bb is not defined
		// console.log(cc);	// 报错	cc is not defined
	}
</script>

[Related recommendations:

javascript video tutorial, web front-end

The above is the detailed content of What is the difference between es5 and es6 scopes. 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
React: Creating Dynamic and Interactive User InterfacesReact: Creating Dynamic and Interactive User InterfacesApr 14, 2025 am 12:08 AM

React is the tool of choice for building dynamic and interactive user interfaces. 1) Componentization and JSX make UI splitting and reusing simple. 2) State management is implemented through the useState hook to trigger UI updates. 3) The event processing mechanism responds to user interaction and improves user experience.

React vs. Backend Frameworks: A ComparisonReact vs. Backend Frameworks: A ComparisonApr 13, 2025 am 12:06 AM

React is a front-end framework for building user interfaces; a back-end framework is used to build server-side applications. React provides componentized and efficient UI updates, and the backend framework provides a complete backend service solution. When choosing a technology stack, project requirements, team skills, and scalability should be considered.

HTML and React: The Relationship Between Markup and ComponentsHTML and React: The Relationship Between Markup and ComponentsApr 12, 2025 am 12:03 AM

The relationship between HTML and React is the core of front-end development, and they jointly build the user interface of modern web applications. 1) HTML defines the content structure and semantics, and React builds a dynamic interface through componentization. 2) React components use JSX syntax to embed HTML to achieve intelligent rendering. 3) Component life cycle manages HTML rendering and updates dynamically according to state and attributes. 4) Use components to optimize HTML structure and improve maintainability. 5) Performance optimization includes avoiding unnecessary rendering, using key attributes, and keeping the component single responsibility.

React and the Frontend: Building Interactive ExperiencesReact and the Frontend: Building Interactive ExperiencesApr 11, 2025 am 12:02 AM

React is the preferred tool for building interactive front-end experiences. 1) React simplifies UI development through componentization and virtual DOM. 2) Components are divided into function components and class components. Function components are simpler and class components provide more life cycle methods. 3) The working principle of React relies on virtual DOM and reconciliation algorithm to improve performance. 4) State management uses useState or this.state, and life cycle methods such as componentDidMount are used for specific logic. 5) Basic usage includes creating components and managing state, and advanced usage involves custom hooks and performance optimization. 6) Common errors include improper status updates and performance issues, debugging skills include using ReactDevTools and Excellent

React and the Frontend Stack: The Tools and TechnologiesReact and the Frontend Stack: The Tools and TechnologiesApr 10, 2025 am 09:34 AM

React is a JavaScript library for building user interfaces, with its core components and state management. 1) Simplify UI development through componentization and state management. 2) The working principle includes reconciliation and rendering, and optimization can be implemented through React.memo and useMemo. 3) The basic usage is to create and render components, and the advanced usage includes using Hooks and ContextAPI. 4) Common errors such as improper status update, you can use ReactDevTools to debug. 5) Performance optimization includes using React.memo, virtualization lists and CodeSplitting, and keeping code readable and maintainable is best practice.

React's Role in HTML: Enhancing User ExperienceReact's Role in HTML: Enhancing User ExperienceApr 09, 2025 am 12:11 AM

React combines JSX and HTML to improve user experience. 1) JSX embeds HTML to make development more intuitive. 2) The virtual DOM mechanism optimizes performance and reduces DOM operations. 3) Component-based management UI to improve maintainability. 4) State management and event processing enhance interactivity.

React Components: Creating Reusable Elements in HTMLReact Components: Creating Reusable Elements in HTMLApr 08, 2025 pm 05:53 PM

React components can be defined by functions or classes, encapsulating UI logic and accepting input data through props. 1) Define components: Use functions or classes to return React elements. 2) Rendering component: React calls render method or executes function component. 3) Multiplexing components: pass data through props to build a complex UI. The lifecycle approach of components allows logic to be executed at different stages, improving development efficiency and code maintainability.

React Strict Mode PurposeReact Strict Mode PurposeApr 02, 2025 pm 05:51 PM

React Strict Mode is a development tool that highlights potential issues in React applications by activating additional checks and warnings. It helps identify legacy code, unsafe lifecycles, and side effects, encouraging modern React practices.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

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

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),