Block Scope
Before ES6 (2015), JavaScript had only Global Scope and Function Scope.
ES6 introduced two important new JavaScript keywords: let and const.
These two keywords provide Block Scope in JavaScript.
Variables declared inside a { } block cannot be accessed from outside the block:
Variables declared with the var keyword can NOT have block scope.
Variables declared inside a { } block can be accessed from outside the block.
{
var x = 2;
}
// x CAN be used here
Variables declared with the var keyword can NOT have block scope.
Variables declared inside a { } block can be accessed from outside the block.
{
var x = 2;
}
// x CAN be used here
Function Scope
JavaScript has function scope: Each function creates a new scope.
Variables defined inside a function are not accessible (visible) from outside the function.
Variables declared with var, let and const are quite similar when declared inside a function.
They all have Function Scope:
function myFunction() {
var carName = "Volvo"; // Function Scope
}
function myFunction() {
let carName = "Volvo"; // Function Scope
}
function myFunction() {
const carName = "Volvo"; // Function Scope
}
Global JavaScript Variables
A variable declared outside a function, becomes GLOBAL.
let carName = "Volvo";
// code here can use carName
function myFunction() {
// code here can also use carName
}
Automatically Global
If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable.
It basically means if we try to define a variable without access specifiers then it is considered as global by default
myFunction();
// code here can use carName
function myFunction() {
carName = "Volvo";
}
To avoid the above situation
- "Strict Mode"-> undeclared variables are not automatically global.
Global Variables in HTML
With JavaScript, the global scope is the JavaScript environment.
In HTML, the global scope is the window object.
- Global variables defined with the var keyword belong to the window object
- Global variables defined with the let keyword do not belong to the window object
Points to Remember->
- Do NOT create global variables unless you intend to.
- Your global variables (or functions) can overwrite window variables (or functions).
- Any function, including the window object, can overwrite your global variables and functions.
The Lifetime of JavaScript Variables
- The lifetime of a JavaScript variable starts when it is declared.
- Function (local) variables are deleted when the function is completed.
- In a web browser, global variables are deleted when you close the browser window (or tab).