search
HomeWeb Front-endFront-end Q&AWhat are the keywords for declaring variables in javascript

What are the keywords for declaring variables in javascript

Jun 09, 2021 pm 03:58 PM
javascriptKeywordsdeclare variables

The keywords for declaring variables in JavaScript are var, let and const. Variables declared with var can be used to save any type of value. The scope of the declaration is the function scope; the scope of the let declaration is the block scope. When declaring a variable with const, the variable must be initialized at the same time, and the value cannot be modified after initialization.

What are the keywords for declaring variables in javascript

The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.

Declare variable keywords var, let and const

ECMAScript variables are loosely typed, that is, variables can be used to save any type of data , each variable is nothing more than a named placeholder used to hold an arbitrary value.

1.var keyword

Variables declared by var can be used to save any type value (unless A special value undefined will be saved during initialization. Like other languages, JavaScript can also assign values ​​to variables while defining them. The variable is defined as a save The variable of the assigned value, because JavaScript is a dynamic language, when initializing the variable, it will not be identified as the assigned data type, it is just a simple assignment. Then not only can the saved value be changed, but the type of the value can also be changed:

var message = "hi";
	message = 100;

1.1.var declaration scope

Use the var operator A defined variable becomes local to the containing function. For example, using var to define a variable inside a function means that the variable will be destroyed when the function exits. I think this is what is called Garbage Collection:

function test( ) {
		vart message = "hi";	//局部变量
	}
test( );
console.log(message);	//报错!

After the function call Variables will be destroyed randomly, so the last line will report an error. However, you can create a global variable when you omit the var operator when defining a variable in a function:

function test( )  {
	message = "hi";	//全局变量
}
test( );
console.log(message);	//"hi"

As long as the function test() is called once, the global variable message will be defined, and it can be Function external access. However, since global variables defined in local scope are difficult to maintain, this is generally not recommended.

1.2. Var declaration promotion

Variables declared using the var keyword will be automatically promoted to the top of the function scope, The so-called "hoisting" (hoist), that is, pulling all variable declarations to the top of the function scope:

function fool( ) {
	console.log(age);
	var age = 28;
}
fool( );	//undefined

No error will be reported here, but undefined will be displayed. When ECMAScript is running, it will be regarded as equivalent to the following code:

function fool( ) {
	var age;
	console.log(age);
	age = 28;
}
fool( );	//undefined

2.let statement

The functions of let and var Pretty much the same, but with very important differences. The most obvious difference is that the scope of the let declaration is block scope, while the scope of the var declaration is the function scope:

if (true) {
	let age = 26;
	console.log(age);	//26
}
console.log(age);	//ReferceError:age没有定义

The scope of the age variable is limited to the inside of the block, so it cannot is referenced outside the if block. Block scope is a subset of function scope, so the same scope restrictions that apply to var also apply to let.

Let also does not allow redundant declarations to appear in the same scope (var can):

var name;
var name;
let age;
let age;	//SyntaxError;标识符age已经声明过了

In addition, redundant declaration errors will not be affected by mixing var and let. These two keywords do not declare variables of different types, they just indicate how the variables exist in the relevant scope.

2.1. Temporary dead zone

Another important difference between let and var is that the variable declared by let will not be used Promoted in the domain:

//name会提升
console.log(name);	//undefined
var name = 'matt';

//name不会提升
console.log(name);	//ReferenceError:name没有定义
let name = 'matt';

2.2. Global declaration

Unlike var, it is declared in the global scope using let Variables will not become attributes of the window object (variables declared with var will):

var name = 'matt';
console.log(window.name);	//'matt'

let name = 'matt';
console.log(window.name);	//undefined

However, let declarations still occur in the global scope, and the corresponding variables will persist within the declaration cycle of the page.

2.3. Conditional declaration

The scope of let is a block, so it is impossible to check whether a variable with the same name has been previously declared using let. At the same time It is also impossible to declare it without declaring it. Using try/catch or typeof operators cannot solve it, because the scope of the let declaration in the conditional block is limited to that block. For this reason, the new ES6 declaration keyword let cannot rely on the conditional declaration pattern.

2.4. let declaration in for loop

When using var, the most common problem is the strange declaration and declaration of iteration variables Modification:

for(var i = 0; i < 5; ++i) {
	setTimeout( () => console.log(i) ,0)
}
//你可能以为会输出0、1、2、3、4
//实际上输出的是5、5、5、5、5

When exiting the loop, the iteration variable stores the value that caused the loop to exit: 5. When the setTimeout timeout logic is executed later, i is the same variable, so the final output is the same value.

    使用let声明迭代变量时,JavaScript引擎在后台会为每个迭代循环声明一个新的迭代变量,每个setTimeout引用的都是不同的变量实例:

for(let i = 0; i < 5; ++i) {
	setTimeout( () => console.log(i) ,0)
}
//会输出0、1、2、3、4

【相关推荐:javascript学习教程

3.const声明

    const的行为与let基本相同,唯一一个重要区别是它声明变量时必须同时初始化变量,且尝试修改const声明的变量会导致运行错误。

    const声明的限制只适用于它指向的变量的引用。如果const变量引用的是一个对象,那么修改这个对象内部的属性并不违反const的限制:

const person = { };
person.name = &#39;matt&#39;;

4.使用建议

let和const是ES6中新增的,从客观上为JavaScript更精确地声明作用域和语义提供更好的支持。

4.1.不使用var

    限制自己只使用let和const有助于提升代码质量,因为变量有了明确的作用域、声明位置,以及不变的值。

4.2.const优先,let次之

    使用const声明可以让浏览器运行时强制保持变量不变,也可以让静态代码分析工具提前发现不合法的赋值操作。因此,我们应该优先使用const来声明变量,只有在提前知道未来会有修改时再使用let。

更多编程相关知识,请访问:编程入门!!

The above is the detailed content of What are the keywords for declaring variables 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