Ram*_*ran 2 javascript variables var typescript angular
var 允许重复声明
xx=1;
xx=2;
console.log(xx+xx);//4
var xx=1;
var xx=2;
console.log(xx+xx);//4
Run Code Online (Sandbox Code Playgroud)
但是let并且const不允许重复减速
const yy=1;
const yy=2;
console.log(yy+yy);//Uncaught SyntaxError: Identifier 'yy' has already been declared",
let zz=1;
let zz=2;
console.log(zz+zz);//Uncaught SyntaxError: Identifier 'zz' has already been declared",Run Code Online (Sandbox Code Playgroud)
我在这里看到了一些类似的东西,
假设采用严格模式,
var将使您在同一范围内重新声明相同的变量。另一方面,let不会。
但是我想知道为什么let并且const不允许重新声明?为什么var呢?JavaScript如何处理这三种类型的减速?
The var keyword was the only way to define variables until 2016*.
No matter where you write var x, the variable x is treated as if it were declared at the top of the enclosing scope (scope for var is "a function").
All declarations of the variable within the same scope are effectively talking about the same variable.
Here is an example... you might think that within the function we overwrite the outer name with fenton, and add Fenton to the inner variable...
var name = 'Ramesh';
function myFunc() {
name = 'fenton';
var name = 'Fenton';
alert(name);
}
myFunc();
alert(name);
Run Code Online (Sandbox Code Playgroud)
In fact, it works just like this... the outer variable is not affected by the inner variable thanks to hoisting.
var name = 'Ramesh';
function myFunc() {
var name;
name = 'fenton';
name = 'Fenton';
alert(name);
}
myFunc();
alert(name);
Run Code Online (Sandbox Code Playgroud)
var keyword at all, in which case they would be added to the global scope. Subtle bugs were often tracked to this.Both let and const are block-scoped, not function-scoped. This makes them work like variables in most other C-like languages. It turns out this is just less confusing than function-scoped variables.
They are also both "more disciplined". They should be declared just once within a block.
The const keyword also disallows subsequent assignments - so you have to declare it with an assignment (i.e. you can't just write const x, you have to write const x = 'Fenton') - and you can't assign another value later.
Some people think this makes the value immutable, but this is a mistake as the value can mutate, as shown below:
const x = [];
// I can mutate even though I can't re-assign
x.push('Fenton');
// x is now ['Fenton']
Run Code Online (Sandbox Code Playgroud)
If you want to avoid some of the more confusing aspects of var, such as multiple declarations all contributing to the same hoisted variable, and function-scope, you should use the newer const and let keywords.
I recommend using const as your default keyword, and upgrade it to let only in cases where you choose to allow re-assignment.