JavaScript Scope JAVASCRIPT
- JavaScript Introduction
- JavaScript Syntax
- JavaScript innerHTML
- JavaScript document.write()
- Javascript - window.alert()
- JavaScript - console.log()
- JavaScript Comments
- JavaScript Variables
- JavaScript Operators
- JavaScript Data Types
- JavaScript Functions
- JavaScript Objects
- JavaScript Events
- JavaScript Strings
- JavaScript String Methods
- JavaScript Numbers
- JavaScript Number Methods
- JavaScript Arrays
- JavaScript Array Methods
- JavaScript Sorting Arrays
- JavaScript Array Iteration
- JavaScript Date Objects
- JavaScript Date Formats
- JavaScript Get Date Methods
- JavaScript Set Date Methods
- JavaScript Math Object
- JavaScript Conditions
- JavaScript Switch
- JavaScript Loop For
- JavaScript While Loop
- JavaScript Break and Continue
- JavaScript Type Conversion
- JavaScript Errors
- JavaScript Scope
- JavaScript this Keyword
- JavaScript Classes
- JavaScript Debugging
- JavaScript - Changing CSS
- JavaScript JSON
JavaScript Scope
JavaScript Scope
JavaScript Function Scope
In JavaScript there are two types of scope:
- Local scope
- Global scope
JavaScript has function scope: Each function creates a new scope.
Scope determines the accessibility (visibility) of these variables.
Variables defined inside a function are not accessible (visible) from outside the function.
Local JavaScript Variables
Variables declared within a JavaScript function, become LOCAL to the function.
Local variables have Function scope: They can only be accessed from within the function.
Local variables are created when a function starts, and deleted when the function is completed.
Example
// code here can NOT use carName
function myFunction() {
var carName = "Volvo";
// code here CAN use carName
}
Global JavaScript Variables
A variable declared outside a function becomes GLOBAL.
A global variable has the global scope: All scripts and functions on a web page can access it.
Example
var carName = "Volvo";
// code here can use carName
function myFunction() {
// code here can also use carName
}