Local Scope and Functions, which excersize shoud i go back to, so i can do this?

Tell us what’s happening:
I don’t understand what to do where should I go back and review?

Your code so far


function myLocalScope() {
'use strict';

// Only change code below this line

console.log(myVar);
}
myLocalScope();

// Run and check the console
// myVar is not defined outside of myLocalScope
console.log(myVar);

// Now remove the console log line to pass the test

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.18362.

Challenge: Local Scope and Functions

Link to the challenge:

Hi.

You have to declare a variable myVar. The variable should be inside the function which means indented by 4 blocks so it has a local scope only. You need just to read some definitions about local and global scope. https://www.w3schools.com/js/js_scope.asp
As an example:

function myFunc() {
    var x = 1;   //local scope variable, it will be executed only inside myFunc
var y = 2;  // global scope, it could be called outside myFunc 
}

If this answer fulfil your needs, please click on solution under my message to close this thread. Happy coding :partying_face:

I believe that this is the page that introduces the concept, so there is no where to go back to.

The key thing that this lesson is trying to let you know is that there is an idea of “local scope” for variables.

  1. Variables defined outside of a function are available to all other functions.
  2. Variables defined inside of a function are only available to that specific function.

I made a simple example to illustrate this.

Notice how if you open up the console, you see an error message that says:

ReferenceError: localVariable is not defined
at https://cdpn.io/boomboom/v2/index.html?editors=0002&key=iFrameKey-c960c2ac-1e04-baca-92bd-ef02c8855e9f:-2

This is because I tried to print localVariable outside of a function.

Going back to the challenge.

First, you need to make sure that myVar is defined inside of myLocalScope.

Next, you should check to see that an error exists when you try to run console.log(myVar);.

Lastly, it is asking you to comment out console.log(myVar); in order to pass the tests.

1 Like

To clarify, both of these variables have scope local to the function body. Global variables are declared outside of any functions.