JS Scope
JS Scope
Scope determines where variables are accessible in your code. JavaScript has global scope, function scope, and block scope.
Global Scope
Variables declared outside functions or blocks are globally accessible.
let site = "W4";
function show() {
console.log(site);
}
show();
Function Scope
Variables declared inside a function are only accessible within that function.
function test() {
let message = "Inside function";
console.log(message);
}
test();
// console.log(message); // Error
Block Scope
Variables declared with let and const are limited to the block in which they are defined.
if (true) {
let value = 10;
const pi = 3.14;
}
// console.log(value); // Error
JS Code Blocks
A block is any code inside curly braces { }. Blocks define scope for let and const.
{
let x = 5;
}
// console.log(x); // Error
However, var does NOT respect block scope.
{
var y = 20;
}
console.log(y); // 20
JS Hoisting
Hoisting is JavaScript's behavior of moving declarations to the top of their scope before execution.
Function Hoisting
greet();
function greet() {
console.log("Hello");
}
Variable Hoisting
var declarations are hoisted but initialized as undefined.
console.log(a); // undefined var a = 5;
let and const are also hoisted but remain in the Temporal Dead Zone (TDZ) until declared.
// console.log(b); // Error let b = 10;
JS Strict Mode
Strict mode enables a stricter parsing and error handling in your JavaScript code.
"use strict"; x = 10; // Error: variable not declared
Strict mode prevents accidental global variables and disallows certain unsafe features.
Strict Mode in Functions
function test() {
"use strict";
let value = 5;
console.log(value);
}
Best Practice
Use let and const instead of var. Enable strict mode in modern projects or rely on ES modules, which use strict mode by default.
Next Step
Continue with JS Dates to learn how JavaScript works with time and date values.