Now we have idea of writing the clear and organized code in JavaScript which is our starting point. In this post, I will be coming the variable scope in JavaScript.
In JavaScript, variable scope can be global or local. Scope is determined by where a variable is declared, and to some extent whether the var keyword is used. By default all variables defined in JavaScript are in global scope or in window scope.
Example 1: Declaring variable in outer scope and modifying within function
Variables defined in global scope or outside functions are always available anywhere in the application until re-declared or modified.
Example 2: Declaring variable in outer scope, but declaring again within function
If any variable is re-declares in local scope of the function then the closest variable in the scope will be accessible to the function.
Example 3: Declaring variable within function and accessing it in outer scope
Variables declared within functions will not be accessible outside the function unless declare in outer scope.
Note: There is no such thing as Scope block {} in JavaScript.
Comments
Post a Comment