Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Please could you explain how it's possible to change the value of a variable with global scope from inside a function?

I don't understand how it's possible to change the value of a variable with global scope from inside a function?

If the variable has already been defined earlier in the code using the let keyword, why does using it without the keyword in a function redefine it?

2 Answers

Hi Tom!

Think of a global variable as one that is implicitly declared as an attribute of the window object.

So let num1 = 5 is in effect the same as window.num1 = 5

The window object can be accessed anywhere in your code.

Consider this:

let num1 = 5; // Declared globally

const morf = function() {
  num1 = 10; // is the same as window.num1 = 10 (global)
  window.num2 = 13; // How to declare a global variable inside a function (must use window)
  let num3 = 15; // without window num3 won't be global
}

morf();

console.log(num1);
console.log(num2);
console.log(num3)

will log:

10
13
Uncaught ReferenceError: num3 is not defined

I hope that helps.

Stay safe and happy coding!

That really helps, thanks Peter.