


Detailed analysis of variable declaration and function declaration promotion in js (with examples)
This article brings you a detailed analysis of variable declarations and function declaration improvements in js (with examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. .
Variable declaration improvement
1. Variable definition
You can use var to define variables. If the variable is not assigned a value, the initial value of the variable is undefined.
2. Variable scope
Variable scope refers to the scope in which the variable works. Variables are divided into global variables and local variables. Global variables are defined globally; local variables are only valid within a function.
In the function body, local variables or parameters with the same name will have higher priority than global variables. That is to say, if there are local variables or parameters with the same name as the global variables in the function, the global variables will be overwritten by the local variables.
All variables not defined using var are considered global variables
3. Function scope and declaration in advance
The function role of JavaScript refers to all variables declared within the function Variables are always defined in the function body, which means that the variables are available before they are declared. This feature is called hoisting, that is, all declarations in JavaScript functions (just declarations, but not assignments) are hoisted. to the top of the function body, leaving the variable assignment operations where they were. Such as the following example:
Note: The declaration in advance is performed during pre-compilation of the JavaScript engine, before the code starts running.
var scope = 'global';function f(){ console.log(scope); var scope = 'local'; console.log(scope); }
Due to the declaration promotion within the function, the above code is actually like this
var scope = 'global';function f(){ var scope; //变量声明提升到函数顶部 console.log(scope); scope = 'local'; //变量初始化依然保留在原来的位置 console.log(scope); }
After such transformation, the answer is very obvious. Since the scope has been defined before the first console.log(scope) statement, but no value has been assigned, the scope's reference is undefined at this time. Before the second console.log(scope) statement, the scope has been assigned a value of 'local', so the output result is local.
Function declaration promotion
Function declaration syntax
f('superman');function f(name){ console.log(name); }
Function expression syntax
f('superman');var f= function(name){ console.log(name); }
When running the above code, an error Uncaught ReferenceError: f will be reported is not defined(...), the error message shows that f is not defined.
Why are there differences between function declarations and function expressions in the same code?
This is because function declaration has a very important feature: function declaration hoisting. The function declaration statement will be hoisted to the top of the external script or external function scope (is it very similar to variable hoisting). It is precisely because of this feature that the function declaration can be placed after the statement that calls it. As in the example below, what should be the final output? :
var getName = function(){ console.log(2); }function getName (){ console.log(1); } getName();
Some people may think that the final output result is 1. Let's analyze it. This example involves variable declaration promotion and function declaration promotion. As mentioned before, the function declaration promotion function getName(){} will be advanced to the top. The function expression var getName = function(){} shows variable declaration promotion. So in this case, getName is also a variable, so the declaration of this variable will also be promoted to the bottom, while the assignment of the variable will still remain at the original position. It should be noted that functions take precedence. Although both function declarations and variable declarations will be promoted, functions will be promoted first, and then variables. Therefore, the above function can be converted into the following:
function getName(){ //函数声明提升到顶部 console.log(1); } var getName; //变量声明提升 getName = function(){ //变量赋值依然保留在原来的位置 console.log(2); } getName(); // 最终输出:2
So the final output is: 2. In the original example, although the function declaration is after the function expression, because the function declaration is promoted to the top, getName is later overwritten by the assignment operation of the function expression, so 2 is output.
related suggestion:
The above is the detailed content of Detailed analysis of variable declaration and function declaration promotion in js (with examples). 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

AI Hentai Generator
Generate AI Hentai for free.

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



Default parameters in C++ provide the ability to specify default values for function parameters, thereby enhancing code readability, simplicity, and flexibility. Declare default parameters: Add the "=" symbol after the parameter in the function declaration, followed by the default value. Usage: When the function is called, if optional parameters are not provided, the default values will be used. Practical case: A function that calculates the sum of two numbers. One parameter is required and the other is optional and has a default value of 0. Advantages: Enhanced readability, increased flexibility, reduced boilerplate code. Note: It can only be specified in the declaration, it must be at the end, and the types must be compatible.

In C++, the order of function declarations and definitions affects the compilation and linking process. The most common is that the declaration comes first and the definition comes after; you can also use "forwarddeclaration" to place the definition before the declaration; if both exist at the same time, the compiler will ignore the declaration and only use the definition.

Solving the "error:useofundeclaredidentifier'variable'" problem in C++ code When programming in C++, we often encounter various errors. One of the common errors is "error:useofundeclaredidentifier'variable'". This error usually means that we are using an undeclared variable in our code. This article will detail

A function declaration informs the compiler of the existence of the function and does not contain the implementation, which is used for type checking. The function definition provides the actual implementation, including the function body. Key distinguishing features include: purpose, location, role. Understanding the differences is crucial to writing efficient and maintainable C++ code.

Function declaration and definition are necessary in C++. Function declaration specifies the return type, name and parameters of the function, while function definition contains the function body and implementation. First declare the function and then use it in your program passing the required parameters. Use the return statement to return a value from a function.

C++ compilation error: function call does not match function declaration, how to solve it? When developing C++ programs, you will inevitably encounter some compilation errors. One of the common errors is that the function call does not match the function declaration. This kind of error widely exists among C++ programmers. Due to not paying attention to the correctness of function declaration, it leads to compilation problems, which ultimately wastes time and energy to fix the problem and affects development efficiency. Ways to avoid this mistake require following some norms and standard practices, let’s take a look at them below. What is a function call versus a function declaration?
![[[nodiscard]] in C++ function declarations: Demystifying the consequences of ignoring return values](https://img.php.cn/upload/article/000/465/014/171455868319393.jpg?x-oss-process=image/resize,m_fill,h_207,w_330)
The [[nodiscard]] attribute indicates that the return value of the function must not be ignored, otherwise it will cause a compiler warning or error to prevent the following consequences: uninitialized exceptions, memory leaks, and incorrect calculation results.

PHP is a very popular web development language that allows developers to create dynamic web applications on the server side. In PHP, a variable is a basic data structure used to store values and data. This article will introduce how to use variables in PHP. Basic Syntax of Variables The syntax for declaring variables in PHP is very simple. Variable names begin with a dollar sign ($), followed by the variable name. Variable names can be a combination of letters, numbers, or underscores, but they must begin with a letter or an underscore. For example, the following code declares a name
