Home > Web Front-end > JS Tutorial > The difference between var and const in js

The difference between var and const in js

下次还敢
Release: 2024-05-01 07:51:17
Original
518 people have browsed it

In JavaScript, the main difference between var and const is that variables declared with var can be reassigned and redeclared, while constants declared with const cannot be modified. Variables declared with var are available within the function or global scope, whereas variables declared with const are only available within the block or module in which they are declared. A var variable can be declared repeatedly in the same scope, while a const variable cannot be declared repeatedly. A var declaration can be anywhere in the block, while a const declaration must be at the top of the block or module.

The difference between var and const in js

The difference between var and const in JavaScript

1. Definition

  • var: Variables declared using var are called variables. It allows reassignment and redeclaration.
  • const: Variables declared using const are called constants. It does not allow reassignment or redeclaration.

2. Declaration scope

  • var: var The variables declared are available in the function or global scope.
  • const: A variable declared with const is only available within the block or module in which it is declared.

3. Reassignment

  • var: var The variables declared can be reassigned at any time.
  • const: const declared variables cannot be reassigned.

4. Re-declare

  • var: var-declared variables can be declared repeatedly in the same scope.
  • const: const declared variables cannot be declared repeatedly in the same scope.

5. Declaration location

  • var: var declaration can appear anywhere in the block.
  • const: The const declaration must appear at the top of the block or module.

6. Code block

  • var: Variables declared by var are available within the code block.
  • const: A variable declared with const is only available within the code block in which it is declared.

7. Reference

  • var: var declared variables can be referenced by other functions and code blocks.
  • const: A variable declared with const can only be referenced within the block or module in which it is declared.

Example

<code class="javascript">// var 变量可以重新赋值
var foo = 10;
foo = 20;

// const 常量不能重新赋值
const bar = 30;
bar = 40; // 报错</code>
Copy after login

The above is the detailed content of The difference between var and const in js. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template