2018-10-12 15:37:13 -04:00
---
title: Compare Scopes of the var and let Keywords
---
2019-07-24 00:59:27 -07:00
# Compare Scopes of the var and let Keywords
2018-10-12 15:37:13 -04:00
2019-07-24 00:59:27 -07:00
---
## Problem Explanation
2018-10-12 15:37:13 -04:00
2019-03-25 23:55:20 +01:00
Change the code so that the variable `i` declared in the if block is separately scoped than the variable `i` declared at the beginning of the function.
2018-10-12 15:37:13 -04:00
2019-07-24 00:59:27 -07:00
---
## Hints
2018-10-12 15:37:13 -04:00
2019-07-24 00:59:27 -07:00
### Hint 1
2018-10-12 15:37:13 -04:00
2019-07-24 00:59:27 -07:00
* _Be certain not to use the `var` keyword anywhere in your code._
### Hint 2
2019-03-25 23:55:20 +01:00
* _Remember that `let`'s scope is limited to the block, function or statement in which you declare it._
2018-10-12 15:37:13 -04:00
2019-07-24 00:59:27 -07:00
---
## Solutions
2018-10-12 15:37:13 -04:00
2019-07-24 00:59:27 -07:00
< details > < summary > Solution 1 (Click to Show/Hide)< / summary >
2018-10-12 15:37:13 -04:00
```javascript
2019-07-24 00:59:27 -07:00
function checkScope() {
"use strict";
let i = "function scope";
if (true) {
let i = "block scope";
console.log("Block scope i is: ", i);
}
console.log("Function scope i is: ", i);
return i;
}
2018-10-12 15:37:13 -04:00
```
2019-07-24 00:59:27 -07:00
#### Code Explanation
2018-10-12 15:37:13 -04:00
2019-03-25 23:55:20 +01:00
By using `let` you can declare variables in relation to their scope.
2018-10-12 15:37:13 -04:00
2019-07-24 00:59:27 -07:00
#### Relevant Links
2019-03-25 23:55:20 +01:00
- ["let" - *MDN Javascript reference* ](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let )
2019-07-24 00:59:27 -07:00
- [Rauschmayer, Axel. "Variables and scoping in ECMAScript 6". *2ality.com*, 2015-02-07. ](http://2ality.com/2015/02/es6-scoping.html ) Accessed 11 Dec 2018.
- [Bos, Wes. "Quick Tip: Use let with for Loops in JavaScript". *wesbos.com*, 16 Aug 2016. ](https://wesbos.com/for-of-es6/ ) Accessed 11 Dec 2018.
< / details >
2019-03-27 09:55:49 -07:00