{"id":8433,"date":"2018-12-24T15:13:36","date_gmt":"2018-12-24T20:13:36","guid":{"rendered":"https:\/\/www.carnaghan.com\/?p=8433"},"modified":"2021-03-06T15:49:10","modified_gmt":"2021-03-06T20:49:10","slug":"javascript-scope","status":"publish","type":"post","link":"https:\/\/www.carnaghan.com\/javascript-scope\/","title":{"rendered":"JavaScript Scope"},"content":{"rendered":"\n
Scope<\/span> determines what variables<\/span> or bindings are available to JavaScript<\/span> within its current context. For example, if a variable<\/span> is defined outside of any functions within your code (often referred to as the main call stack), these variables<\/span> are available to all other code embedded within other blocks and functions. Variables<\/span> defined in main are often referred to as ‘Global Variables<\/span>‘ because they are globally available throughout your application. But what about those variables<\/span> that are defined within functions?<\/p>\n\n\n\n The term Lexical Scope<\/span> is used to define how binding visibility is implemented within JavaScript<\/span>. If a variable<\/span> is defined within a function, it will only be available to that function and any other blocks or functions defined within it.<\/strong> Let’s go back to our call stack example from the last lesson, make some changes to the way we structured the functions. In addition, we will define some variables<\/span>.<\/p>\n\n\n\n In the above example we are defining variable a within our main call stack, which in turn becomes a global variable<\/span>. This means a will be available within both first and second functions. In the first function we are defining a second variable called b with a value<\/span> of 2. Because a was defined in the main call stack, it is also available to first, therefore the console.log will yield the results of both a and b. At this stage we define a function called second within first, which now has access<\/span> to both a and b. In addition we define a third variable c and are able to view the results of all three once second is called from within first. Let’s look back at the call stack diagram and see how these variables<\/span> are available within the different stages.<\/p>\n\n\n\n A major change we made from the last lesson was to embed second<\/em> within first<\/em>, instead defining it within the main call stack and invoking it within first. If second was defined within the main call stack, it would not have access to b.<\/p><\/blockquote>\n\n\n\nLexical Scope<\/span><\/h2>\n\n\n\n
\nlet a = 1;\nconsole.log(a);\n\nfunction first() { \/\/ function defined within main call stack and has access to a and local variables\n let b = 2;\n console.log(a,b);\n \n function second() { \/\/ function defined within first and has access to a and b and any local variables\n let c = 3;\n console.log(a,b,c);\n }\n second()\n}\n\nfirst()<\/code><\/pre>\n\n\n\n