FAQ: Scope - Scope Pollution

This community-built FAQ covers the “Scope Pollution” exercise from the lesson “Scope”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Web Development

Introduction To JavaScript

FAQs on the exercise Scope Pollution

There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

In this exercise, I reassigned stars inside the block of the function callMyNightSky. How come I can access it login it to the console outside the function? Isnt it a local variable now that it is reassigned inside the block?

1 Like

the scope is determined when you define the variable, when you assign the variable a new value it will just keep its scope

having said that, updating global variables is bad practice

3 Likes

There is an error in the lesson Scope - Scope Pollution.

On page 6 of 7, Step 2 asks us to write a new let variable lightWaves and set it equal to 'Northern Lights' . Writing the requested code, and saving this step, produces an error, because the program wants us to simultaneously have the NEXT step completed (which is grayed out and states to write console.log() to log the value of the block variable inside the if block).

The program only allows us to continue when Step 3 is completed at Step 2, or when we request the solution.

Is it correct to say that an array with a single element does not need to use the let or const declaration?
ref: step 5 of 12

Any variable, regardless the object it references or where it is declared will rise to the top of the scope chain (global namespace) if we do not use a declaration keyword. This is known as polluting global scope and something to be avoided at most, if not all turns.

The only place where let has no real purpose is in global scope. We use the keyword just so we get into the habit of using it in functions, loops and conditional blocks which will prevent the variable from leaking into parent or global scope.

Even an empty array should still be declared with a keyword. const is okay if we never wish to replace the structure, only the values. If we intend to re-use the variable in the event it is no longer of use, then use let.

let a = []
// some code to populate, manipulate and poll the array
a = null

Notice that the data type is changed but the above is perfectly valid. We have effectively erased the array from existence but still have that variable in play.

4 Likes

“The only place where let has no real purpose is in global scope.”

Thank you.

2 Likes

I followed the instructions in 5/7, but my global variable (stars) was never reassigned and remained ‘North Star’ on the second console call.

const satellite = ‘The Moon’
const galaxy = ‘The Milky Way.’
const stars = ‘North Star’

const callMyNightSky = () => { const stars = ‘Sirius’;
return 'Night Sky: ’ + satellite + ', ’ + stars + ', and ’ + galaxy; }
console.log(callMyNightSky())
console.log(stars)
function logVisibleLightWaves() {const lightWaves =‘Moonlight’
console.log(lightWaves) }
logVisibleLightWaves()

Additionally when I declare the new variable ‘star’ and do not use the let keyword, I get a
'TypeError: Assignment to constant variable at callMyNightSky ’

I think I solved my own problem. The problem was that I declared the global variable with “const” not “let”.

1 Like

That is because the function is looking outside at stars, which is already declared a constant and cannot be changed.

Be sure to read and follow the instructions. If the author wants to show you how variables with the same name can have two different scopes, then use let inside the function. That will shadow the global so it cannot be seen from inside the function.

hi there, on pg 5/7 in the scope module we’re overriding the global variable ‘the north star’ with the local variable ‘sirius’ inside the code block of the function. Can anyone explains how local variables take precedence over their global antecedents?

When a variable of the same name as a global is declared inside a function (including in the parameter list) it is said to shadow the global making it inaccessible from within the function body.

We can still access it, but must provide the window context.

let bar = 0
const foo = function (bar) {
    console.log(bar);
    console.log(window.bar);
}
foo(42)
// <- 42
// <- 0
      
console.log(bar) 
// <- 0
1 Like

This seems counter intuitive to me. In Python, reassigning the variable within the function would not change the global instance. Confusing!

Agree, and updating global variable isn’t something you should do

having said that, we can have two variables with the same name using different scope in JS:

let x = 3;

function myFunction(){
  let x = 3;
  x += 2;
  console.log(x);
}
myFunction();

console.log(x);

the let keyword is critical here, ensuring a new variable (with the appropriate scope rules)

1 Like

Thanks, I’ve just done the next lesson and realised using the ‘let’ means you’re defining a new variable (of the same name, but with a local scope) instead of assigning a new value to the global variable.
Got it. Cheers!

1 Like

3 posts were split to a new topic: Reassign stars - Scope Pollution

Hello,
Suppose we have the following pieces of source code.
Code 1–>

let num = 50;

const logNum = () => {
  num = 100; // Take note of this line of code
  console.log(num);
};

logNum(); // Prints 100
console.log(num); // Prints 100

Code 2–>

let num = 50;

const logNum = () => {
  let num = 100; // Take note of this line of code
  console.log(num);
};

logNum(); // Prints 100
console.log(num); // Prints 50

Comparing the two pieces of code, I noticed that there is a small difference, and that is the let keyword inside the function body. My question is, why the value of the variable num in the second example is changed to “50” when the let keyword is present?

Hello, @madaskalas.

The num declared inside the function using let is a new variable. It is scoped to the function. When you console.log(num); outside the function. You are referring to the variable declared outside the function. If you tried this:

const logNum = () => {
  let num = 100; // Take note of this line of code
  console.log(num);
};

logNum(); // Prints 100
console.log(num); // ReferenceError: num is not defined 

You would get the ReferenceError because num is only defined inside the function. In your Code 2-> you have two separate variables that happen to have the same name. Something like this might cause confusion:

let num = 50;

const logNum = () => {
  let num = 100; // Take note of this line of code
  num = 25;
  console.log(num);
};

logNum(); // Prints ?
console.log(num); // Prints ?

The expected output is now somewhat ambiguous.

Just for fun:

let num = 50;

const logNum = () => {
  let num = 100; // Take note of this line of code
  num = 25;
  causeTrouble()
  console.log(num);
};

const causeTrouble = () => num *= 2

logNum(); // Prints ?
console.log(num); // Prints ?

I’m not actually trying to cause confusion. Just illustrating the confines of scope, and that it can be confusing to re-use the same name for variables that are assigned different values in the same program. It can be done, but it gets confusing.

1 Like

Thank you @midlindner for your answer. That helped me.

However, I wonder why using the let keyword somewhat impacts the scope of the variable. Without using the let keyword , it seems that the variable num is defined in the global scope, even if it is being declared inside the function body, which is somewhat strange.

Can you help to clarify this issue? Thanks in advance.

<Code 1 -->

let num = 50;

const logNum = () => {
  num = 100; // Take note of this line of code
  console.log(num);
};

logNum(); // Prints 100
console.log(num); // Prints 100