JS Scope
Scope = Visibility
Scope determines the accessibility (visibility) of variables.
JavaScript variables have 3 types of scope:
- Global scope
- Function scope
- Block scope
Global scope
var x = 1; // Global scope
let y = 2; // Global scope
const z = 3; // Global scope
A variable declared outside a function, becomes GLOBAL.
let carName = "Volvo";
// code here can use carName
function myFunction() {
// code here can also use carName
}
Function scope
Variables declared within a JavaScript function are LOCAL to the function
function myFunction1() {
var carName = "Volvo"; // Function Scope
}
function myFunction2() {
let carName = "Volvo"; // Function Scope
}
function myFunction3() {
const carName = "Volvo"; // Function Scope
}
Block scope
Variables declared with let and const inside a code block are "block-scoped," meaning they are only accessible within that block.
This helps prevent unintended variable overwrites and promotes better code organization:
{
let x = 2;
}
// x can NOT be used here
let x = 5
{
x = 2
}
// x = 5
let x = 5
function myFunc() {
x = 2
}
myFunc()
// x = 2
let x = 5;
function myfunc() {
const x = 3;
}
myfunc();
// x = 5
Variables declared with the var keyword can NOT have block scope (Not recommended).
{
var x = 2
}
// x CAN be uded here
Automatically Global
If you assign a value to a variable that has not been declared, it will become a GLOBAL variable.
This code example will declare a global variable carName, even if the value is assigned inside a function.
myFunction();
// code here can use carName
function myFunction() {
carName = "Volvo";
}
Strict mode
In "Strict Mode", undeclared variables are not automatically global.
"use strict";
x = 3.14; // This will cause an error because x is not declared
Global variables defines with the var keyword belong to the window object