Q: 1 Which of the statement is correct in JavaScript regarding var and let keywords?
var has global scope, and let has block scope
var has block scope, and let has global scope
var has local scope, and let has global scope
var has global scope, and let also has global scope
[ Option A ]
In JavaScript, the main difference between var and let lies in their scope. A variable declared with var has either global scope (if declared outside a function) or function scope (if declared inside a function). It does not follow block scope, meaning it can still be accessed outside the block { } in which it is defined.
On the other hand, a variable declared with let is block scoped, which means it is only accessible within the block { } where it is declared.
// Using var
if (true) {
var x = 10;
}
console.log(x); // No Error, print 10 (var is not block scoped).
// Using let
if (true) {
let y = 20;
}
console.log(y); // Error, y is not defined (let is block scoped).
Thank you so much for taking the time to read my Computer Science MCQs section carefully. Your support and interest mean a lot, and I truly appreciate you being part of this journey. Stay connected for more insights and updates! If you'd like to explore more tutorials and insights, check out my YouTube channel.
Don’t forget to subscribe and stay connected for future updates.