How to use variables
- The scope of a variable or function determines what code has access to it.
- Variables that are created inside a function are local variables, and local variables can only be referred to by the code within the function.
- Variables created outside of functions are global variables, and the code in all functions has access to all global variables.
- If you forget to code the var keyword in a variable declaration, the JavaScript engine assumes that the variable is global. This can cause debugging problems.
- In general, it’s better to pass local variables from one function to another as parameters than it is to use global variables. That will make your code easier to understand with less chance of errors.
Example 1: In this example, we will declare variables in the global scope so that they can be accessed anywhere in the program.
let petName = 'Rocky' // Global variable
myFunction()
function myFunction() {
fruit = 'apple'; // Considered global
console.log(typeof petName +
'- ' +
'My pet name is ' +
petName)
}
console.log(
typeof petName +
'- ' +
'My pet name is ' +
petName +
'Fruit name is ' +
fruit)
Output
string- My pet name is Rocky string- My pet name is RockyFruit name is apple
Explanation: We can see that the variable petName is declared in the global scope and is easily accessed inside functions. Also, the fruit was declared inside the function without any keyword so it was considered global and was accessible inside another function.
Example 2: In this example, we will declare variables in the local scope and try to access them at different scopes.
myfunction();
anotherFunc();
let petName;
function myfunction() {
let petName = "Sizzer"; // local variable
console.log(petName);
}
function anotherFunc() {
let petName = "Tom"; // local variable
console.log(petName);
}
console.log(petName);
Output
Sizzer Tom undefined
Explanation: We can see that the variable petName is declared in global scope but not initialized. Also, the functions are accessing the inner variable where each function has its own value for the variable petName.
Contact Us