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

The difference between var, let and const in js

不言
Release: 2018-07-05 17:53:18
Original
2129 people have browsed it

This article mainly introduces the differences between var, let, and const in js. It has a certain reference value. Now I share it with everyone. Friends in need can refer to it.

//1.var定义的变量可以修改,如果不初始化会输出undefined,不会报错。
var a;
console.log(a); //undefined


//2.let是块级作用域,函数内部使用let定义后,对函数外部无影响。
let c = 3;
console.log(c)

function change(){
let c = 6;
console.log(c)
}
change();

(1)只要块级作用域于中存在let命令,它所声明的变量就绑定在这个区域中,不再受外部的影响。

var a = 10;
{
  console.log(a);   //undefined   (作用域内部变量不受外部影响,还有就是let不存在变量提升,所以才会报未定义)
  let a = 3;
  console.log(a);    //3
}

(2)let不允许在同一个作用域内,重复声明同一个变量
{
  var a = 2;
  let a  = 2;
  console.log(a)     // Error: Identifier 'a' has already been declared
}


//3.const定义的变量不可以修改,而且必须初始化。
//const b; //这样定义不对,必须赋值初始化
const b=1;
Copy after login

The above is the entire article Content, I hope it will be helpful to everyone’s learning. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

js exports the table tag of the page to csv

Introduction to getters and setters in JavaScript

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

Related labels:
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