--- id: 587d7b87367417b2b2512b3f title: Explore Differences Between the var and let Keywords challengeType: 1 videoUrl: '' localeTitle: 探索var和let关键字之间的差异 ---
使用var关键字声明变量的最大问题之一是您可以在没有错误的情况下覆盖变量声明。
var camper = 'James';
var camper = 'David';
console.log(camper);
// 输出 'David'
正如您在上面的代码中看到的那样, camper变量最初被声明为James ,然后被重写为David 。在小型应用程序中,您可能不会遇到此类问题,但是当您的代码变大时,您可能会意外覆盖您不打算覆盖的变量。因为这种行为不会引发错误,所以搜索和修复错误变得更加困难。
在ES6中引入了一个名为let的新关键字,用var关键字解决了这个潜在的问题。如果要在上面代码的变量声明中用let替换var ,结果将是一个错误。
let camper = 'James';
let camper = 'David'; // 抛出一个错误
您可以在浏览器的控制台中看到此错误。因此与var不同,使用let ,具有相同名称的变量只能声明一次。注意"use strict" 。这启用了严格模式,可以捕获常见的编码错误和“不安全”操作。例如:
"use strict";
x = 3.14; // 抛出一个错误,因为 x 未定义
## Instructions
更新代码,使其仅使用let关键字。
## Tests
```yml tests: - text: var在代码中不存在。 testString: 'getUserInput => assert(!getUserInput("index").match(/var/g),"var does not exist in code.");' - text: catName应该是Oliver 。 testString: 'assert(catName === "Oliver", "catName should be Oliver.");' - text: quote应该是"Oliver says Meow!" testString: 'assert(quote === "Oliver says Meow!", "quote should be "Oliver says Meow!"");' ```
## Challenge Seed
```js var catName; var quote; function catTalk() { "use strict"; catName = "Oliver"; quote = catName + " says Meow!"; } catTalk(); ```
## Solution
```js // solution required ```