Learn

In our theoretical apartment building, you have your own apartment. It has stuff in it that is yours. Other people in the building can’t access it. This is like functional scope. You have access to your stuff inside your apartment, and in the building – but not anyone else’s apartment.

When we write variables inside a function, only that function has access to its own variables. Therefore, they are in the functional scope.

In addition to a function having access to its own variables, it also has access to variables in the global scope.

In the last exercise we created both variables in the global scope. That is, laundryRoom and mailRoom are accessible from anywhere in our program.

Now, let’s make two variables within a functional scope.

Instructions

1.

Write a function named myApartment before the console.logs from the last exercise.

2.

Inside of the function, write a variable named mailBoxNumber and set it equal to Box 3.

Also, you’re lucky enough to have in-unit laundry, so let’s re-assign laundryRoom inside our function to: laundryRoom = 'In-unit'.

3.

Inside the function, use console.log to print out both variables, like this:

console.log('Mail box: ' + mailBoxNumber + ', Laundry:' + laundryRoom);
4.

Now, let’s try to see the mailBoxNumber outside the function. On the last line of the program, write:

console.log(mailBoxNumber);
5.

Nothing showed up in the console! That’s right, and it means that JavaScript does not have access to the variable, since it is hidden away in the myApartment function.

To see the hidden variables inside the function, delete the console.log on mailBoxNumber in the global scope, and call the myApartment function instead.

Take this course for free

By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Already have an account?