- Object/Oriented JavaScript
- Stoyan Stefanov
- 408字
- 2021-08-13 19:25:53
Scope of Variables
I t is important to note, especially if you have come to JavaScript from another language, that variables in JavaScript are not defined in a block scope, but in a function scope. This means that if a variable is defined inside a function, it's not visible outside of the function. However, a variable defined inside an if
or a for
code block is visible outside the code block. The term "global variables" describes variables you define outside of any function, as opposed to "local variables" which are defined inside a function. The code inside a function has access to all global variables as well as to its own local variables.
In the next example:
- The function
f()
has access to the variableglobal
- Outside of the function
f()
, the variablelocal
doesn't exist
var global = 1; function f() { var local = 2; global++; return global; } >>> f();
2
>>> f();
3
>>> local
local is not defined
It is also important to note that if you don't use var
to declare a variable, this variable is automatically assigned global scope. Let's see an example:

What happened? The function f()
contains the variable local
. Before calling the function, the variable doesn't exist. When you call the function for the first time, the variable local
is created with a global scope. FThen if you access local
outside the function, it's available.
Tip
B est Practice Tips
- Minimize the number of global variables. Imagine two people working on two different functions in the same script and they both decide to use the same name for their global variable. This could easily lead to unexpected results and hard-to-find bugs.
- Always declare your variables with the
var
statement.
Here's an interesting example that shows an important aspect of the local versus global scoping.
var a = 123; function f() { alert(a); var a = 1; alert(a); } f();
You might expect that the first alert()
will display 123 (the value of the global variable a
) and the second will display 1 (the local a
). This is not the case. The first alert will show "undefined". This is because inside the function the local scope is more important than the global scope. So a local variable overwrites any global variable with the same name. At the time of the first alert()
a
was not yet defined (hence the value undefined) but it still existed in the local space.
- AI圖像處理:Photoshop+Firefly后期處理技術基礎與實戰
- Django 1.2 E/commerce
- ImageMagick Tricks
- 中文版Illustrator CC基礎培訓教程(移動學習版)
- Dreamweaver CC實例教程(第5版·微課版)
- Puppet 2.7 Cookbook
- Adobe創意大學Illustrator CS5 產品專家認證標準教材
- Java EE 6 with GlassFish 3 Application Server
- Adobe創意大學Photoshop產品專家認證標準教材(CS6修訂版)
- PostgreSQL 9.0 High Performance
- 抖音+剪映+Premiere短視頻制作從新手到高手(第2版)
- Origin 2022科學繪圖與數據分析
- After Effects 2023實訓教程
- 老郵差 Photoshop數碼照片處理技法 圖層篇(修訂版)
- Maya 2022從新手到高手