0
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

This is an example from a codecademy lesson on scope. I thought that num would only be 100 inside of the function body (local) and that outside of the function body (global) it would remain 50? Can someone explain what is happening?

I have asked ChatGPT about this and it said that the example is incorrect however I am not sure because each codecademy lesson is made by several people with extreme thought and effort put into the lesson and I would be surprised if it was actually wrong.

  • `num` is a global variable so it can be accessed anywhere. It's also _one_ variable, so it can't manifest two different variables based on scopes. So, once it becomes 100, it's 100. – technophyle Jul 31 '23 at 18:51
  • `num` would be only 100 inside `logNum` if you defined another scope for it. eg. `let num = 100`. IOW: Scope is defined in the block you define the variable, after that it's global to all scopes below. ps. a block scope that `let` uses, is each `{}` pair. eg. `{let x=1; {console.log(x); { let x=2; console.log(x); } console.log(x)}}` would give you 1,2,1 – Keith Jul 31 '23 at 18:53
  • 1
    I don't think you can depend on ChatGPT to know what is correct or incorrect. It doesn't know how to program. It knows how to string words together in a manner that imitates the way people string words together. – Heretic Monkey Jul 31 '23 at 18:54
  • 1
    Does this answer your question? [What is the scope of variables in JavaScript?](https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) – Heretic Monkey Jul 31 '23 at 18:54

1 Answers1

0

num is a global variable so it can be accessed anywhere. Looks like you already understand this.

It's also one variable, so it can't manifest two different values based on scopes. Once it becomes 100, it's 100:

// num is set to 100, and there's no way it can be 50 again,
// unless it's explicitly set to that value again
num = 100;

If there's another num variable defined under a local scope, it could have a different value, but this does not mean num has two values depending on the scope. It just means there are incidentally two variables with the same name (which is not a good practice btw).

See below:

let num = 50;
 
const logNum = () => {
  let num = 50; // this is a separate variable with local scope
  num = 100; // Take note of this line of code
  console.log(num);
}
 
logNum(); // Prints 100
console.log(num); // Prints 50
technophyle
  • 7,972
  • 6
  • 29
  • 50
  • 1
    Variable shadowing would be good reference -> https://en.wikipedia.org/wiki/Variable_shadowing – Keith Jul 31 '23 at 19:00