Scope
The scope defines where variables and functions are accessible inside of your program. In JavaScript, there are two kinds of scope - global scope, and function scope. According to the official spec.
// Function scope
function iHaveScope() {
// local function scope
function iHaveNestedScope() {
// nested local function scope
}
}
Block scopes are what you get when you use if statements, for statements, and the like. You can also use them stand-alone with a simple begin-end curly braces {}, not to be confused with empty object literals.
// Block scope
var a = {} // empty object literal
{ var a } // undefined object in a block scope
if (3 == '3') {
// block scope for the if statement
}
for (var i=0; i<10; i++) {
// block scope for the for statement
}
Global JavaScript Variables
A variable declared outside a function becomes GLOBAL. A global variable has a global scope: All scripts and functions on a web page can access it.
var carName = "Volvo";
// code here can use carName
function myFunction() {
// code here can also use carName
}
Last updated
Was this helpful?