


What are the differences between the two types of variable scopes in JavaScript?
Difference: In the global scope, variables are visible throughout the page script and can be freely accessed. In the local scope, variables can only be visible inside the declared function, and are not allowed to be accessed outside the function; after the function is executed, the local scope is destroyed.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
Variable scope, which can be called "variable scope (Scope)", refers to the effective range that a variable can access in the program, also known as the visibility of the variable.
Scope
1. What is Scope
Generally speaking , the name used in a piece of program code is not always valid and available, and the code scope that limits the availability of this name is the scope of this name.
JS scope: It is the scope of the code name (variable)
The purpose of the scope: to improve the reliability of the program, and more importantly, to reduce naming conflicts
2. Classification of JS scope (before ES6)
JS scope can be divided into two categories: global scope and local scope (function Scope)
1) Global scope:
The JS code written directly in the script tag is the global scope;
Or in a separate JS file.
The global scope is created when the page is opened and destroyed when the page is closed;
There is a global object window in the global scope (representing a browser window, created by the browser ), can be used directly.
In the global scope,
- All created variables will be saved as properties of the window object.
- All created functions will be saved as methods of the window object.
2) Local scope (function scope):
Inside the function is the local scope, this The name of the code only works inside the function
The function scope is created when the function is called. After the function is executed, the function scope is destroyed;
A new one will be created each time the function is called. Function scopes are independent of each other.
Example analysis:
In this example, there is a num variable in the local scope in the un function, and there is also a num variable in the global scope of the script tag.
(One is in the global scope and the other is in the local scope. Although the variable names of the two variables conflict, it has no effect.)
So, in different functions Under the domain, variables with the same names are not affected, which effectively reduces naming conflicts.
<script> var num = 10; function nu(){ var num = 20; console.log(num); } nu(); console.log(num); </script>
There is no block-level scope in JS at this stage (before ES6). The block-level scope is enclosed by curly brackets ({}).
2. Scope of variables
JavaScript variables can be divided into global variables and local variables:
Global variables: variables are in the entire page script They are all visible and can be accessed freely; their scope is the global scope.
Local variables: Variables can only be visible inside the declared function, and are not allowed to be accessed outside the function; their scope is the local scope.
Example 1
The following example demonstrates the relationship between global variables and local variables.
var a = 1; //声明并初始化全局变量 function f(){ //声明函数 document.write(a); //显示undefined var a = 2; //声明并初始化局部变量 document.write(a); //显示 2 } f(); //调用函数
Since a local variable a with the same name is declared inside the function, during the pre-compilation period, JavaScript uses this variable to override the influence of the global variable inside the function. At the beginning of execution, local variable a is not assigned a value, so the value of local variable a read in the first line of code in the function is undefined. When the 2nd line of code of the function is executed, the local variable is assigned a value of 2, so it is displayed as 2 in the 3rd line.
Example 2
The following example demonstrates the consequences of not explicitly declaring local variables.
var jQuery = 1; (function () { jQuery = window.jQuery = window.$ = function(){}; })() document.write(jQuery); //显示函数代码:function(){}
Therefore, using global variables within a function body is a dangerous behavior. To avoid such problems, you should get into the habit of explicitly declaring local variables using the var statement within the function body.
[Recommended learning: javascript advanced tutorial]
The above is the detailed content of What are the differences between the two types of variable scopes in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

The variable scope in PHP is divided into local (within the function), global (accessible within the program), and class scope (accessible within the class instance). The global keyword can declare local variables as global variables, and the static keyword can declare local variables as static variables, retaining their values between function calls.

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

In Go, the function life cycle includes definition, loading, linking, initialization, calling and returning; variable scope is divided into function level and block level. Variables within a function are visible internally, while variables within a block are only visible within the block.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest
