Execution Context And Scope
The execution context of a variable or function defines the scope of the function and variables. The global execution context is the outermost one. Each function has its own execution context.
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<script type="text/javascript">
var name = "blue";
function changeName(){
if (name === "blue"){
name = "red";
} else {
name = "blue";
}
}
changeName();
document.writeln(name);//red
</script>
</head>
<body>
</body>
</html>
The following code has three level of execution context:
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<script type="text/javascript">
var name = "JavaScript";
function changeName(){
var anotherName = "HTML";
function swapNames(){
var tempName = anotherName;
document.writeln("tempName:"+tempName);
anotherName = name;
name = tempName;
//name, anotherName, and tempName are all accessible here
}
//name and anotherName are accessible here, but not tempName
swapNames();
}
//only name is accessible here
changeName();
document.writeln(name);//HTML
</script>
</head>
<body>
</body>
</html>