2018-10-10 18:03:03 -04:00
---
id: 56533eb9ac21ba0edf2244bf
2021-02-06 04:42:36 +00:00
title: Local Scope and Functions
2018-10-10 18:03:03 -04:00
challengeType: 1
2020-04-29 18:29:13 +08:00
videoUrl: 'https://scrimba.com/c/cd62NhM'
forumTopicId: 18227
2021-01-13 03:31:00 +01:00
dashedName: local-scope-and-functions
2018-10-10 18:03:03 -04:00
---
2020-12-16 00:37:30 -07:00
# --description--
2021-02-06 04:42:36 +00: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-12-16 00:37:30 -07:00
2021-02-06 04:42:36 +00:00
Here is a function `myTest` with a local variable called `loc` .
2020-04-29 18:29:13 +08:00
```js
function myTest() {
var loc = "foo";
console.log(loc);
}
myTest(); // logs "foo"
console.log(loc); // loc is not defined
```
2021-02-06 04:42:36 +00:00
`loc` is not defined outside of the function.
2018-10-10 18:03:03 -04:00
2020-12-16 00:37:30 -07:00
# --instructions--
2018-10-10 18:03:03 -04:00
2021-02-06 04:42:36 +00: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.
2018-10-10 18:03:03 -04:00
2021-02-06 04:42:36 +00:00
**Note:** The console will still have 'ReferenceError: myVar is not defined', but this will not cause the tests to fail.
2018-10-10 18:03:03 -04:00
2020-12-16 00:37:30 -07:00
# --hints--
2018-10-10 18:03:03 -04:00
2021-02-06 04:42:36 +00:00
The code should not contain a global `myVar` variable.
2018-10-10 18:03:03 -04:00
```js
2021-02-06 04:42:36 +00:00
function declared() {
myVar;
}
assert.throws(declared, ReferenceError);
2018-10-10 18:03:03 -04:00
```
2021-02-06 04:42:36 +00:00
You should add a local `myVar` variable.
2018-10-10 18:03:03 -04:00
```js
2021-02-06 04:42:36 +00:00
assert(
/functionmyLocalScope\(\)\{.+(var|let|const)myVar[\s\S]*}/.test(
__helpers.removeWhiteSpace(code)
)
);
2018-10-10 18:03:03 -04:00
```
2021-01-13 03:31:00 +01:00
# --seed--
## --seed-contents--
```js
function myLocalScope() {
// Only change code below this line
console.log('inside myLocalScope', myVar);
}
myLocalScope();
// Run and check the console
// myVar is not defined outside of myLocalScope
console.log('outside myLocalScope', myVar);
```
2020-12-16 00:37:30 -07:00
# --solutions--
2020-04-29 18:29:13 +08:00
2021-01-13 03:31:00 +01:00
```js
function myLocalScope() {
// Only change code below this line
var myVar;
console.log('inside myLocalScope', myVar);
}
myLocalScope();
// Run and check the console
// myVar is not defined outside of myLocalScope
console.log('outside myLocalScope', myVar);
```