In JavaScript, scope determines the visibility and accessibility of variables and functions in your code. There are two types of scope in JavaScript: global scope and local scope.
For example:
var globalVariable = "I am global!";
function globalFunction() {
console.log("Hello from globalFunction!");
}
console.log(globalVariable); // Output: "I am global!"
globalFunction(); // Output: "Hello from globalFunction!"
For example:
function localFunction() {
var localVariable = "I am local!";
console.log(localVariable);
}
localFunction(); // Output: "I am local!"
console.log(localVariable); // ReferenceError: localVariable is not defined
For example:
console.log( 'Code is Poetry' );function functionScope() {
var x = 10;
if (true) {
var y = 20;
console.log(x); // Output: 10
console.log(y); // Output: 20
}
console.log(x); // Output: 10
console.log(y); // Output: 20
}
functionScope();
console.log(x); // ReferenceError: x is not defined
console.log(y); // ReferenceError: y is not defined
For example:
function blockScope() {
let x = 10;
if (true) {
let y = 20;
const z = 30;
console.log(x); // Output: 10
console.log(y); // Output: 20
console.log(z); // Output: 30
}
console.log(x); // Output: 10
console.log(y); // ReferenceError: y is not defined
console.log(z); // ReferenceError: z is not defined
}
blockScope();
Understanding scope is important in JavaScript to avoid naming collisions and to write code that is easier to maintain and debug.
Learners TV is a website that is designed to educate users and provide instructional material on particular subjects and topics.