2.3.27 Function Scope

If we create a variable within a block of code, it is scoped to that block. This is different than in C#. Code blocks are marked with curly braces ( { } ). So a function has a block of code because it uses curly braces to define it. Let’s look at the previous code sample…


Note: Due to how StackBlitz works, the error will show a different error. When opened and viewed through the browser, it should show as followed in the image below.

Image of the console showing an error stating 'Uncaught reference error : newNum is not defined at cswd1.html:16'

Notice that we are trying to access the newNum variable that is in the function block of code…within the curly braces. It is scoped to that block…encapsulated. So it cannot be accessed outside of that block of code.

Image showing that newNum cannot be accessed. Statement reads, 'Uncaught reference error: newNum is not defined'