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

Difference between Function Scope and Block Scope

i would like to have a detailed difference between both please :)

2 Answers

Steven Parker
Steven Parker
243,318 Points

Function scope means something is available anywhere in the function where it is declared. Block Scope means it is available only within the block (inside a pair of braces) where it is declared. For example:

function test() {
  if (true) {
    var func = 1;     // "var" gives function scope
    let block = 2;    // "let" gives block scope
    // here, func is 1 and block is 2
  }
  // here, func is still 1 but block is not defined
}

test();
// here, neither func or block is defined

may i know how do you take these snippets ccoz i cant see an option for upload a piece of my code ??

Steven Parker
Steven Parker
243,318 Points

The code is just copy/pasted in, using the instructions for code formatting in the Markdown Cheatsheet pop-up below the "Add an Answer" area. :arrow_heading_down:   Or you can watch this video on code formatting.

Thanks man i got it