2018-09-30 23:01:58 +01:00
---
id: 56533eb9ac21ba0edf2244bf
title: Local Scope and Functions
challengeType: 1
2019-02-14 12:24:02 -05:00
videoUrl: 'https://scrimba.com/c/cd62NhM'
2019-07-31 11:32:23 -07:00
forumTopicId: 18227
2018-09-30 23:01:58 +01:00
---
## Description
< section id = 'description' >
Variables which are declared within a function, as well as the function parameters have < dfn > local< / dfn > scope. That means, they are only visible within that function.
Here is a function < code > myTest< / code > with a local variable called < code > loc< / code > .
2019-05-17 06:20:30 -07:00
```js
function myTest() {
var loc = "foo";
console.log(loc);
}
myTest(); // logs "foo"
console.log(loc); // loc is not defined
```
2018-09-30 23:01:58 +01:00
< code > loc< / code > is not defined outside of the function.
< / section >
## Instructions
< section id = 'instructions' >
2020-04-29 13:09:48 +02:00
The editor has two `console.log` s to help you see what is happening. Check the console as you code to see how it changes. Declare a local variable `myVar` inside `myLocalScope` and run the tests.
**Note:** The console will still have 'ReferenceError: myVar is not defined', but this will not cause the tests to fail.
2018-09-30 23:01:58 +01:00
< / section >
## Tests
< section id = 'tests' >
```yml
2018-10-04 14:37:37 +01:00
tests:
2019-11-27 02:57:38 -08:00
- text: The code should not contain a global < code > myVar</ code > variable.
2020-04-29 13:09:48 +02:00
testString: |
function declared(){
myVar;
}
assert.throws(declared, ReferenceError);
2019-11-27 02:57:38 -08:00
- text: You should add a local < code > myVar</ code > variable.
2020-09-17 19:08:01 +05:00
testString: assert(/functionmyLocalScope\(\)\{.+(var|let|const)myVar[\s\S]*}/.test(__helpers.removeWhiteSpace(code)));
2019-02-05 14:40:58 +08:00
2018-09-30 23:01:58 +01:00
```
< / section >
## Challenge Seed
< section id = 'challengeSeed' >
< div id = 'js-seed' >
```js
function myLocalScope() {
2020-03-02 23:18:30 -08:00
// Only change code below this line
2018-10-08 01:01:53 +01:00
2020-04-29 13:09:48 +02:00
console.log('inside myLocalScope', myVar);
2018-09-30 23:01:58 +01:00
}
myLocalScope();
// Run and check the console
// myVar is not defined outside of myLocalScope
2020-04-29 13:09:48 +02:00
console.log('outside myLocalScope', myVar);
2018-09-30 23:01:58 +01:00
```
< / div >
< / section >
## Solution
< section id = 'solution' >
```js
function myLocalScope() {
2018-10-08 01:01:53 +01:00
2020-04-29 13:09:48 +02:00
// Only change code below this line
2018-09-30 23:01:58 +01:00
var myVar;
2020-04-29 13:09:48 +02:00
console.log('inside myLocalScope', myVar);
2018-09-30 23:01:58 +01:00
}
myLocalScope();
2020-04-29 13:09:48 +02:00
// Run and check the console
// myVar is not defined outside of myLocalScope
console.log('outside myLocalScope', myVar);
2018-09-30 23:01:58 +01:00
```
< / section >