search
HomeWeb Front-endFront-end Q&AWhat is scope in javascript

What is scope in javascript

Jan 18, 2022 pm 05:50 PM
javascriptScope

In JavaScript, scope is the accessible range of variables (objects, functions), and the effective range of variables that can be read and written in script code; scope can control the visibility and life cycle of variables. .

What is scope in javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

Almost all languages ​​have the concept of scope. Simply put, scope (scope) is the accessible scope of a variable, that is, the scope controls the visibility and life cycle of the variable. .

In JavaScript, objects and functions are also variables.

Before ECMAScript6, the scope of variables was mainly divided into global scope and local scope (also called function scope); in ECMAScript6 and after, the scope of variables was mainly divided into There are three types: global scope, local scope and block-level scope.

The variables in the corresponding scope are called global variables, local variables and block-level variables respectively.

  • Global variables are declared outside all functions;

  • Local variables are variables declared within the function body or named parameters of the function;

  • Block-level variables are variables declared in the block and are only valid in the block.

The scope of a variable is closely related to the declaration method. Variables declared using var have global scope and function scope, and there is no block-level scope; variables declared using let and const have global scope, local scope and block-level scope.

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
			var v1 = "JavaScript"; //全局变量
			let v2 = "JScript"; //全局变量
			let v3 = "Script"; //全局变量
			scopeTest(); //调用函数
			function scopeTest() {
				var lv = "aaa"; //局部变量
				var v1 = "bbb"; //局部变量
				let v2 = "ccc"; //局部变量
				if (true) {
					let lv = "123"; //块级变量
					console.log("块内输出的lv = " + lv); //123
				}
				console.log("函数体内输出的lv = " + lv); //aaa
				console.log("函数体内输出的v1 = " + v1); //bbb
				console.log("函数体内输出的v2 = " + v2); //ccc
				console.log("函数体内输出的v3 = " + v3); //Script
				//v4为全局变量,赋值在后面,因而值为undefined
				console.log("函数体内输出的v4 = " + v4);
			}
			var v4 = "VBScript"; //全局变量
			console.log("函数体外输出的lv = " + lv); //① 报ReferenceError错误
			console.log("函数体外输出的v1 = " + v1); //JavaScript
			console.log("函数体外输出的v2 = " + v2); //JScript
			console.log("函数体外输出的v3 = " + v3); //Script
			console.log("函数体外输出的v3 = " + v4); //VBScript
		</script>
	</body>
</html>

The above script code declares 4 global variables, 3 local variables and 1 block-level variable respectively. Outside the scopeTest function, variables v1, v2, v3 and v4 are global variables; within the scopeTest function body, lv and v2 are global variables; in the if judgment block, lv is a block-level variable.

We see that local variables v1 and v2 have the same names as global variables v1 and v2. In the scopeTest function body, local variables v1 and v2 are valid, so the output results of these two variables in the function body are "bbb" " and "ccc"; outside the function body, the global variables v1 and v2 are valid, so outside the function body, the output results of these two variables are "JavaScript" and "JScript" respectively.

In addition, the block-level variable lv and the local variable lv have the same name. In the if judgment block, the block-level variable lv is valid, so the output result in the block is "123", while outside the block, the local variable lv Valid, the output result of the lv variable is "aaa".

In addition, the global variables v3 and v4 are not overwritten in the function body, so the value of the global variable is output, so the output result of v3 in the function body and outside the body is "Script", and the v4 variable The assignment is after the function call, so the output result of v4 in the function body is "undefined", while the output outside the function body is after the declaration, so the result is "VBScript". lv is a local variable, so accessing it outside the function will report a "ReferenceError" error.

After the above code is run in the Chrome browser, open the browser's console and you can see the output shown in the figure below.

What is scope in javascript

The reason for the error in line 28:

The lv variable is a local variable and is invalid after leaving the function. Comment this line of code and then run it. At this time, open the browser console and you will see:

What is scope in javascript

[Related recommendations: javascript learning tutorial

The above is the detailed content of What is 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
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.

React Fragments UsageReact Fragments UsageApr 02, 2025 pm 05:50 PM

React Fragments allow grouping children without extra DOM nodes, enhancing structure, performance, and accessibility. They support keys for efficient list rendering.

React Reconciliation ProcessReact Reconciliation ProcessApr 02, 2025 pm 05:49 PM

The article discusses React's reconciliation process, detailing how it efficiently updates the DOM. Key steps include triggering reconciliation, creating a Virtual DOM, using a diffing algorithm, and applying minimal DOM updates. It also covers perfo

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
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

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

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

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

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function