In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the knowledge of "how to understand the variables, scope and promotion in JavaScript". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Variables are a basic component of many programming languages and the first and most important concept that beginners need to learn. There are many different variable attributes in JavaScript, as well as some rules that must be followed when naming variables. In JavaScript, there are three keywords for declaring variables-- var, let, and const-- each keyword affects how the code interprets the variable differently.
This tutorial will introduce what variables are, how to declare and name variables, and further explore the differences between var, let, and const. We will also review the impact of ascension and the importance of global and local scopes to variable behavior.
Understanding variables
Variables are named containers for storing values. A piece of information that we may refer to multiple times can be stored in a variable for later use or modification. In JavaScript, the value contained in a variable can be any JavaScript data type, including a number, string, or object.
Before the ECMAScript 2015 (ES6) language specification on which today's JavaScript is based, there was only one way to declare variables-- using the var keyword. As a result, most older code and learning resources will only use var for variables. We will discuss the differences between the var, let, and const keywords in a separate section below.
We can use var to demonstrate the concept of the variable itself. In the following example, we will declare a variable and assign a value to it.
/ / Assign the string value Sammy to the username identifiervar username = "sammy_shark"
This statement consists of the following parts:
Declare variables using the var keyword
Variable name (or identifier), user name
Assignment operation, represented by = syntax
Assigned value "sammy_shark"
Now we can use username in our code. JavaScript will remember that username represents the string value sammy_shark.
/ / Check if variable is equal to valueif (username = = "sammy_shark") {console.log (true);}
Output:
True
As mentioned earlier, variables can be used to represent any JavaScript data type. In this case, we will declare variables using strings, numbers, objects, Boolean values, and null values.
/ / Assignment of various variablesvar name = "Sammy"; var spartans = 300 red kingdoms = ["mammals", "birds", "fish"]; var poem = {roses: "red", violets: "blue"}; var success = true;var nothing = null
Using console.log, we can see the values contained in specific variables.
/ / Send spartans variable to the consoleconsole.log (spartans)
Output: 300
Variables store the data in memory, which can be accessed and modified later. Variables can also be reassigned and given a new value. The following simplified example shows how to store a password in a variable and then update it.
/ / assign var password = "hunter2" to the password variable; / / reassign the variable value password = "hunter3" with a new value; console.log (password)
Output:
'hunter3'
In a real program, passwords are likely to be stored securely in the database. However, this example illustrates a situation in which we may need to update the value of the variable. The value of password is hunter2, but we reassigned it to hunter3, a value that JavaScript has recognized since then.
Named variable
Variable names are called identifiers in JavaScript. We discussed some rules for naming identifiers when understanding JavaScript syntax and code structure, which are summarized as follows:
Variable names can only consist of letters (amurz), numbers (0-9), dollar sign ($), and underscores (_).
Variable names cannot contain any white space characters (tabs or spaces)
The number cannot start with the name of any variable
Reserved keywords cannot be used as the name of a variable
Variable names are case sensitive
JavaScript is also used to using hump case (sometimes stylized as hump case) in the names of functions and variables declared with var or let. This is a practice of lowercase the first word and then capitalizing the first letter of each subsequent word with no spaces in the middle. With a few exceptions, most very large variables follow this convention. The names of constant variables declared with the const keyword are usually capitalized.
This may seem like a lot of rules to learn, but it will soon become the second nature of writing valid and regular variable names.
The difference between var, let and const
JavaScript has three different keywords to declare variables, which adds additional complexity to the language. The difference between the three is based on scope, promotion, and redistribution.
Var functional scope YesYesYeslet blocking scope NoYesNoconst blocking range NoNoNo
You may want to know which of these three methods should be used in your program. A generally accepted practice is to use const as much as possible, and to use let in the case of loops and redistributions. In general, var can be avoided in addition to dealing with legacy code.
Variable scope
Scope in JavaScript refers to the current context of the code, which determines the accessibility of variables to JavaScript. The two types of scope are local and global:
Global variables are variables declared outside the block
A local variable is a variable declared within a block
In the following example, we will create a global variable.
/ / initialize a global variable var creature = "wolf"
We know that variables can be reassigned. Using a local scope, we can actually create a new variable with the same name as a variable in the external scope without changing or reassigning the original value.
In the following example, we will create a global species variable. Inside the function is a local variable with the same name. By sending them to the console, we can see how the value of the variable varies according to the range, and the original value does not change.
/ / initialize a global variable var species = "human"; function transform () {/ / initialize a local, function-scoped variable var species = "werewolf"; console.log (species);} / record global and local variables console.log (species); transform (); console.log (species)
Output:
Humanwerewolfhuman
In this case, the local variable is functional scoped. Variables declared with the var keyword are always function scoped, which means that they recognize the function as having an independent scope. Therefore, variables in this local scope cannot be accessed from the global scope.
However, the new keywords let and const are block-scoped. This means creating a new local scope from any type of block, including function blocks, if statements, for, and while loops.
To illustrate the difference between function-scoped variables and block-scoped variables, we will use let to assign a new variable in the if block.
Var fullMoon = true;// initializes a global variable let species = "human"; if (fullMoon) {/ / initializes a block-scoped variable let species = "werewolf"; console.log (`block. Lupin is currently a ${species}. `);} console.log (`It is not a full moon. Lupin is currently a ${species}. `)
Output:
It is a full moon. Lupin is currently a werewolf.It is not a full moon. Lupin is currently a human.
In this example, the species variable has one value global (human) and another value local (werewolf). Var however, if we use it, there will be different results.
/ / use var to initialize a variable var species = "human"; if (fullMoon) {/ / try to create a new variable in a block var species = "werewolf"; console.log (`block. Lupin is currently a ${species}. `);} console.log (`It is not a full moon. Lupin is currently a ${species}. `)
Output:
It is a full moon. Lupin is currently a werewolf.It is not a full moon. Lupin is currently a werewolf.
In the result of this example, both global and block-wide variables end with the same value. This is because instead of using var to create a new local variable, you reassign the same variable in the same scope. Var does not recognize whether it belongs to a different new scope. It is generally recommended to declare block-scoped variables because the code they generate is less likely to inadvertently override the value of the variable.
Variable lifting
So far, in most examples, we have declared a variable using var and initialized it with a value. After declaration and initialization, we can access or reassign variables.
If we try to use a variable before it is declared and initialized, it will return undefined.
/ / try to use it console.log (x) before declaring the variable; / / assign the variable var x = 100
Output:
Undefined
However, if the var keyword is omitted, the variable is no longer declared, but is initialized. It will return a ReferenceError and stop the execution of the script.
/ / try to use it console.log (x) before declaring a variable; / / assign a variable without var to x = 100
Output:
ReferenceError: x is not defined
The reason is promotion, which is a behavior of JavaScript, where variables and function declarations are moved to the top of their scope. Because only the actual declaration is suspended and not initialized, the value in the first example returns an undefined value.
To demonstrate this concept more clearly, here is the code we wrote and how JavaScript interprets it.
/ / The code we wroteconsole.log (x); var x = 100; How JavaScript interpreted itvar x console.log (x); x = 100
JavaScript saves x as memory as a variable before executing the script. Because it is still called before it is defined, the result is undefined rather than 100. However, it does not cause ReferenceError and stop the script.
Although the var keyword does not actually change the location of the var, it helps to indicate how promotion works. However, this behavior can cause problems, because the programmer writing this code may want the output of x to be true rather than undefined.
In the next example, we can also see how ascension leads to unpredictable results:
/ / initialize xvar x = 100 * function hoist () {/ / conditions if (false) {var x = 200;} console.log (x);} hoist () that should not affect the coding result in a global scope
Output:
Undefined
In this example, we declare that x is 100 globally. According to the if statement, x can be changed to 200, but because the condition is false, it should not affect the value of x.
This unpredictable behavior may cause bug in the program. Because let and const are block-scoped, they will not be promoted in this way, as shown below.
/ / initialize xlet x = true;function hoist () {/ / initialize x if (3 = 4) {let x = false;} console.log (x) in the global scope;} hoist ()
Output:
True
Repeated declarations of variables (which are possible in var) will throw an error in let and const.
/ / attempt to override the variable var x = 1 position var x = 2 position console.log (x) declared with var
Output: 2
/ / an attempt was made to override the variable declared with let, let y = 1 position let y = 2 position console.log (y)
Output:
Uncaught SyntaxError: Identifier 'y'has already been declared
In summary, variables introduced using var may be affected by promotion, which is a mechanism in JavaScript where variable declarations are stored in memory. This may result in undefined variables in the code. The introduction of let and const solves this problem by throwing an error when trying to use the variable before declaring it or declaring it multiple times.
Constant
Many programming languages have constants, which are values that cannot be modified or changed. In JavaScript, const identifiers are modeled based on constants and cannot be reassigned to values assigned to const.
It is a common convention to capitalize all const identifiers. This distinguishes them from other variable values.
In the following example, we use the const keyword to initialize the variable SPECIES to a constant. An attempt to reassign variables will result in an error.
/ / assign the value const SPECIES = "human" to const; / / try to reassign the value SPECIES = "werewolf"; console.log (SPECIES)
Output:
Uncaught TypeError: Assignment to constant variable.
Since the values cannot be reassigned, they need to be declared and initialized at the same time, or an error will be thrown.
/ / declare, but do not initialize constconst TODO;console.log (TODO)
Output:
Uncaught SyntaxError: Missing initializer in const declaration
Values that cannot be changed in programming are called immutable values, while values that can be changed are mutable. Although const values cannot be reassigned, they are mutable because the properties of objects declared with const can be modified.
/ / create a CAR object with two attributes: const CAR = {color: "blue", price: 15000} / / modify the property of CAR CAR.price = 200000 share console.log (CAR)
Output:
{color: 'blue', price: 20000}
Constants are very useful to make it clear to yourself and other programmers in the future that expected variables should not be reassigned. If you want to modify a variable in the future, you may want to use let to declare the variable.
This is the end of the content of "how to understand variables, scopes and promotions in JavaScript". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.