官术网_书友最值得收藏!

Understanding the scope of variables

Understanding the scope of variables is very important in JavaScript to gain a better hold of the language. Scope may be referred to as a bucket in which your variable or your function exists. Unlike Java and other popular languages, JavaScript follows function-level scoping as opposed to block-level scoping (which is now introduced in es6). So, this means that the variables you define will be limited to a scope that is bound to its parent function.

Consider the following code snippet:

var outer = 10; 
function myFunction() { 
   var inner = 2; 
   console.log(inner);// 2 
   console.log(outer);// 10 
}myFunction();console.log(inner); 

When you run the preceding code, we can see the scope of the inner variable is limited to the parent function named myFunction. It won't be accessible outside it and will provide a referenceError notification. Also, the variables available in outer scopes are available in function scopes, and you don't need to make any extra effort to access them, as you have seen with the variable named outer in the preceding example.

An important thing to discuss in this context is the use of the var keyword. JavaScript won't complain if you miss var while declaring a new variable. But things can get really bad if that happens. See the following example:

(function (){   
    (function (){  
          a = 10;   
    })();  
})();  
console.log(a);// 10 

Here, as the var keyword was skipped along with the variable declaration inside the inner function, JavaScript considered that this variable should be searched in its parent scopes, then attached it to the global scope, and ended up making it available everywhere. So, to avoid such issues with the code, it is always useful if you pass your code through code quality tools such as JSHint. The preceding code structure may have confused you, as it used self-invoked functions just to induce scopes.

Now with the arrival of es6, you can declare variables with the block scope rather than only the function scope. To understand the block level scoping, let's go through the following example:

 

The only difference in preceding snippets is the declaration of variable i. The i variable is not accessible outside the for loop block.

For more details regarding let refer the link: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/let

So that was all about scope of variables. JavaScript supports a number of data types. Let's take a look at them.

主站蜘蛛池模板: 绵竹市| 马边| 峨眉山市| 彩票| 曲麻莱县| 界首市| 且末县| 金湖县| 天全县| 秦皇岛市| 巫溪县| 雷州市| 古浪县| 海阳市| 仁寿县| 伊宁市| 金山区| 神农架林区| 漳州市| 三门峡市| 黑水县| 麻江县| 靖州| 石嘴山市| 磐石市| 安庆市| 葫芦岛市| 集安市| 东乡族自治县| 安塞县| 海南省| 曲阜市| 顺昌县| 长丰县| 乌拉特前旗| 新民市| 阳江市| 潮州市| 连云港市| 金坛市| 东安县|