Scopes
A Scope is simply an area in the code where a variable can be accessed or used.
There are two types of scopes:
- Global Scope;
- Local Scope.
If a variable is defined inside a block of code (between curly brackets {}), it is said to have a local scope. This means that it can only be accessed from inside that function or code block, or any nested blocks:
123456789101112function exampleFunc() { let exampleVariable = 10; console.log(exampleVariable); // Valid if(10 + 10 == 20) { console.log(exampleVariable); // Valid } } exampleFunc(); console.log(exampleVariable); // Shows error
A variable that is defined outside of any code block is said to have a Global Scope, and it can be accessed from anywhere:
123456789101112let exampleVariable = 10; function exampleFunc() { console.log(exampleVariable); // Valid if(10 + 10 == 20) { console.log(exampleVariable); // Valid } } exampleFunc(); console.log(exampleVariable); // Valid
A variable defined in a lower (nested) scope cannot be accessed from a higher (parent) scope:
1234567891011function exampleFunc() { if(10 + 10 == 20) { let exampleVariable = 10; console.log(exampleVariable); // Valid } console.log(exampleVariable); // Shows error } exampleFunc(); console.log(exampleVariable); // Shows error
Tak for dine kommentarer!
Spørg AI
Spørg AI
Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat
Fantastisk!
Completion rate forbedret til 1.33
Scopes
Stryg for at vise menuen
A Scope is simply an area in the code where a variable can be accessed or used.
There are two types of scopes:
- Global Scope;
- Local Scope.
If a variable is defined inside a block of code (between curly brackets {}), it is said to have a local scope. This means that it can only be accessed from inside that function or code block, or any nested blocks:
123456789101112function exampleFunc() { let exampleVariable = 10; console.log(exampleVariable); // Valid if(10 + 10 == 20) { console.log(exampleVariable); // Valid } } exampleFunc(); console.log(exampleVariable); // Shows error
A variable that is defined outside of any code block is said to have a Global Scope, and it can be accessed from anywhere:
123456789101112let exampleVariable = 10; function exampleFunc() { console.log(exampleVariable); // Valid if(10 + 10 == 20) { console.log(exampleVariable); // Valid } } exampleFunc(); console.log(exampleVariable); // Valid
A variable defined in a lower (nested) scope cannot be accessed from a higher (parent) scope:
1234567891011function exampleFunc() { if(10 + 10 == 20) { let exampleVariable = 10; console.log(exampleVariable); // Valid } console.log(exampleVariable); // Shows error } exampleFunc(); console.log(exampleVariable); // Shows error
Tak for dine kommentarer!