JavaScript scope
JavaScript Scope
JavaScript has two scopes: global and local. A
variable that is declared outside a function definition is a global variable,
and its value is accessible and modifiable throughout your program. A variable
that is declared inside a function definition is local. It is created and
destroyed every time the function is executed, and it cannot be accessed by any
code outside the function. JavaScript does not support block scope (in which a
set of braces {. . .} defines a new scope), except in the special case of block-scoped
variables.
Local JavaScript Variables:
Example:
// code here can not use carName
function myFunction() {
var carName = "Volvo";
// code here can use carName
}
function myFunction() {
var carName = "Volvo";
// code here can use carName
}
Since
local variables are only recognized inside their functions, variables with the
same name can be used in different functions.
Local
variables are created when a function starts, and deleted when the function is
completed.
Global JavaScript Variables:
Example:
var
carName = " Volvo";
// code
here can use carName
function
myFunction() {
// code here can use carName
}
Automatically Global:
If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable.
Example:
myFunction();
// code
here can use carName
function
myFunction() {
carName = "Volvo";
}
Global
Variables in HTML:
With
JavaScript, the global scope is the complete JavaScript environment.
In HTML,
the global scope is the window object. All global variables belong to the
window object.
Example
<!DOCTYPE
html>
<html>
<body>
<p>
In HTML,
all global variables will become window variables.
</p>
<p
id="demo"></p>
<script>
var
carName = "Volvo";
// code
here can use window.carName
document.getElementById("demo").innerHTML
= "I can display " + window.carName;
</script>
</body>
</html>
The
Lifetime of JavaScript Variables:
The
lifetime of a JavaScript variable starts when it is declared.
Local
variables are deleted when the function is completed.
Global
variables are deleted when you close the page.
Function Arguments:
Function arguments (parameters) work as local variables inside
functions.
Block-Scoped Variables:
Internet Explorer 11 introduces support for "let" and "const", which are
block-scoped variables. For these variables, the braces {. . .} define a new
scope. When you set one of these variables to a particular value, the value
applies only to the scope in which it is set.
Example:
let x =
10;
var y =
10;
{
let x = 5;
var y = 5;
{
let x = 2;
var y = 2;
document.write("x: " + x +
"<br/>");
document.write("y: " + y +
"<br/>");
// Output:
// x: 2
// y: 2
}
document.write("x: " + x +
"<br/>");
document.write("y: " + y +
"<br/>");
// Output:
// x: 5
// y: 2
}
document.write("x:
" + x + "<br/>");
document.write("y:
" + y + "<br/>");
//
Output:
// x: 10
// y: 2
Subscribe to:
Post Comments
(
Atom
)
No comments :
Post a Comment