FAQ: Scope - Scope Pollution

To avoid the variable stars being reassigned to the different value ‘Sirius’, couldn’t we write the code as const stars = ‘The North Star’?

I think it’s interesting to note the results of

const satellite = 'The Moon';
const galaxy = 'The Milky Way';
let stars = 'North Star';

const callMyNightSky = (stars) => {
  stars = 'Sirius';
	return 'Night Sky: ' + satellite + ', ' + stars + ', ' + galaxy;
};

console.log(callMyNightSky(stars));
console.log(stars);

logs

Night Sky: The Moon, Sirius, The Milky Way
North Star

Declaring a parameter ‘stars’ appears equivalent to saying ‘let stars …’ within the function scope.

close, but not entirely true. let has block-scope, parameters have function scope. Which is also a sort of block, but a very specific one

1 Like

Thanks for the clarification! Had this not been explicitly pointed out to me, I’m sure it would have me pulling out my hair someday.

1 Like

Hi, can you please can you please clarify whether variables created using the keyword var have block scope?

let and const have true block-scope:

if (true) {
   let x = 3;
}

console.log(x); // will result in an error

var has a functional scope, so the only block var has a block scope, is within a function:

const example = () => {]
   var x  = 3;
}

Of course, the local variable has nothing to do with the global variable with the same name, right? They simply have the same name but different scopes. Depending on where you try to access the variable, it will either be the global or the local one

Yes, that’s a good point. Most of the times, if you really needed to declare variables in the global scope, you would most probably use the const keyword to make it a constant variable

Ola! fiquei na duvida quanto ao uso de variáveis globais na explicação diz: quando vc declara variaveis globais elas vão para o namespace global what!!! onde é isso? quer dizer esta fora do escopo da funcao? e outra entendi o porque de nao declarar variavel no escopo global porem uma vez definida essa colisao acontece por conta do esquecimento do uso de let, isso porque quando se usa let nao ocorre vazamento, certo? e no caso do esquecimento vaza o que faz com que ocasiona?

This was my question, I thought the scope of the new stars variable was strictly local since its in the code block. But I guess since it was defined above the code block it , it’s always a global scope…

Ok, just to see if I got this down, if the var x outside of the block = 4, and everything else was the same, the console would print 3? If the var x outside of the block was a const x = 4 and everything else was the same, I assume that would produce an error?

simple enough to try:

var x = 4;

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

console.log(x); // logs: 4

there are two things important here, first:

x += 2;

will favor the local variable (x = 3) over the global variable (x = 4)

we can have a global variable and a local variable with the same name.

no, for the reasons mentioned above

Ok, I didn’t find an answer in the thread, so sorry if it’s a duplicate. but I don’t get one thing.
As explained in the lesson, this is scope polution. The global variable is overwritten in the function:

let num = 50;
 
const logNum = () => {
  num = 100; 
  console.log(num);
};
 
logNum(); // Prints 100
console.log(num); // Prints 100

But if I pass the variable as a parameter, it does not get overwritten, the global variable remains the same and the function variable lives it’s own life. Why is that so?

let num = 50;
 
const logNum = (num) => {
  num = 100; // I think this is reassignment, not redeclaration, am I wrong?
  console.log(num);
  return num // even this does not change the global variable
};
 
logNum(num); // Prints 100
console.log(num); // Prints 50. Why?

Is it that when I call logNum(num), a new instance of num (another variable with the same name) is created and it is destroyed when function finishes? But I return num back to the global scope, how do I lose it?

because the parameter has a local scope, and a global and local variable with the same name can co-exists.

the value is returned to the function call:

logNum(num); // Prints 100

but you do nothing with the returned value, you could then capture it in a variable or log it:

let otherNum = logNum(num);
1 Like

so why not just create a variable inside the function block with the same name? Instead of stars= put let stars= That way the stars variable inside the function returns a different value than the one outside the block.

const satellite = ‘The Moon’;

const galaxy = ‘The Milky Way’;

let stars = ‘North Star’;

const callMyNightSky = () => {

let stars = ‘Sirius’

return 'Night Sky: ’ + satellite + ', ’ + stars + ', ’ + galaxy;

};

console.log(callMyNightSky()); //returns Night Sky: The Moon, Sirius, The Milky Way

console.log(stars) //returns North Star

Depends on what you want to achieve. I think for this lesson its important you understand the difference

1 Like

Makes sense. I jumped ahead of myself and didn’t finish the lesson before asking my question. Thank you! :grinning_face_with_smiling_eyes:

ok so just to finish the train of thought here. Why does it correct the issue if I add “let” prior to stars in the function code block?

Regarding the following example:

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

The lesson says this:

  • The reassignment inside logNum() affects the global variable num .

my question is, how can a locally defined variable change a global variable, regardless of having the same name? my understanding is that local variables are contained within their function’s code block…same name or not. confused here…

^bump

i would like to know this as well, seems like a pretty salient point about JS functionality…