The goal of this tutorial is to provide an understanding of the scope control in HTML and scripting languages, such as JavaScript. We will delve into the different scopes of variables and how to control them. After reading this tutorial, you will be able to define, manipulate and control scopes within your code effectively.
At the end of this tutorial, you will be able to:
Before you start, you should be familiar with:
In programming, scope defines the accessibility or visibility of variables, objects, functions in some particular part of your code during runtime. In other words, it determines the portion of the code where a variable or a function can be accessed.
There are two types of scope in JavaScript:
Global Scope: Variables defined outside any function, block, or module scope have global scope. They can be accessed from any function or block in the program.
Local Scope: Variables defined inside a function or a block have local scope. They can only be accessed within that function or block.
var
, let
, or const
to avoid them automatically becoming global.var globalVar = "I am global!"; // This is a global variable
function exampleFunction() {
console.log(globalVar); // Logs: "I am global!"
}
exampleFunction();
In this example, globalVar
is a global variable and can be accessed anywhere in the code, including within exampleFunction
.
function exampleFunction() {
var localVar = "I am local!"; // This is a local variable
console.log(localVar); // Logs: "I am local!"
}
exampleFunction();
console.log(localVar); // Throws an error
Here, localVar
is only available within the exampleFunction
function. Trying to log it outside of the function results in an error because it is not defined in that scope.
In this tutorial, we've learned about the concept of scope in HTML and JavaScript, including the differences between global and local scope, and how to control scope. The key points we've covered are:
To solidify your understanding, try out the following exercises:
Exercise 1: Declare a global variable and use it in a function. Log the variable before and after the function call.
Exercise 2: Declare a local variable in a function and try to log it outside the function. Observe the error and explain why it occurs.
Exercise 3: Create a function with a local variable. Create another function nested inside the first one and try to access the local variable of the first function.
Remember, practice is key when it comes to programming! Keep practicing and exploring more about scopes in different scenarios.