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
---
2020-11-27 19:02:05 +01:00
# --description--
2018-09-30 23:01:58 +01:00
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.
2020-11-27 19:02:05 +01:00
Here is a function `myTest` with a local variable called `loc` .
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
```
2020-11-27 19:02:05 +01:00
`loc` is not defined outside of the function.
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
# --instructions--
2020-04-29 13:09:48 +02:00
2020-11-27 19:02:05 +01: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.
2020-04-29 13:09:48 +02:00
**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
2020-11-27 19:02:05 +01:00
# --hints--
2019-02-05 14:40:58 +08:00
2020-11-27 19:02:05 +01:00
The code should not contain a global `myVar` variable.
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
```js
function declared() {
myVar;
}
assert.throws(declared, ReferenceError);
2018-09-30 23:01:58 +01:00
```
2020-11-27 19:02:05 +01:00
You should add a local `myVar` variable.
```js
assert(
/functionmyLocalScope\(\)\{.+(var|let|const)myVar[\s\S]*}/.test(
__helpers.removeWhiteSpace(code)
)
);
```
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
# --seed--
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
## --seed-contents--
2018-09-30 23:01:58 +01:00
```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
```
2020-11-27 19:02:05 +01:00
# --solutions--
2018-09-30 23:01:58 +01:00
```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
```