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

C#

Ali Dahud
Ali Dahud
3,459 Points

Can you explain to me in more depth?

what is a variable scope? because in the video it's explained poorly Steven Parker

1 Answer

Steven Parker
Steven Parker
231,261 Points

Sure, I'll give it a shot, but for future questions try giving the whole community some time to answer before tagging anyone specifically. There are lots of folks wiling to help.

So "variable scope" is basically a way to describe what part of the program a variable can be accessed in. The most common cases are "global scope", which means the variable can be accessed anywhere, "function scope" where the variable can be accessed only within a specific function, and "block scope" where the variable can be accessed only inside a code block (between a pair of braces {}). Here's some examples:

var globby = 2;                 // global scope

function test(x) {
  if (x == 1) {
    var funky = 3;              // function scope
    let blocky = 4;             // block scope
    console.log(typeof globby); // "number"
    console.log(typeof funky);  // "number"
    console.log(typeof blocky); // "number"
  }
  console.log(typeof globby);   // "number"
  console.log(typeof funky);    // "number" (still in scope)
  console.log(typeof blocky);   // "undefined"
}

test(1);
console.log(typeof globby);     // "number"
console.log(typeof funky);      // "undefined"
console.log(typeof blocky);     // "undefined"
Ali Dahud
Ali Dahud
3,459 Points

Thank you but you’re so responsive and you’re explaining it extremely well.

Ali Dahud
Ali Dahud
3,459 Points

And if we can’t be in direct contact then why wouldn’t I?

Steven Parker
Steven Parker
231,261 Points

That's very nice, and I'm flattered. But I'm sure input from various sources would be beneficial to your learning. Give the community as a whole a chance.

Plus I do answer questions where I'm not tagged. :wink: