Consider the following JavaScript code:
var x = 10;
function test() {
var x = 20;
console.log(x);
}
test();
console.log(x);What will be printed to the console?
var x = 10; function test() { var x = 20; console.log(x); } test(); console.log(x);
Remember that variables declared inside a function have local scope and do not affect the global variable.
The function test has a local variable x set to 20, so console.log(x) inside the function prints 20. Outside the function, the global x is still 10, so console.log(x) prints 10.
Look at this code:
function setValue() {
y = 5;
}
setValue();
console.log(y);What will be the output?
function setValue() { y = 5; } setValue(); console.log(y);
Variables assigned without var, let, or const inside functions become global.
Because y is assigned without declaration inside the function, it becomes a global variable. So after calling setValue(), y exists globally with value 5.
Choose the correct statement about global scope in JavaScript.
Think about how var and let differ in global scope.
Variables declared with var at the top level become properties of the global object (like window in browsers). Variables declared with let or const do not become global object properties. Functions declared inside blocks are block-scoped, not global. const inside functions is local to that function.
Consider this code:
let count = 0;
function increment() {
count++;
}
increment();
console.log(count);What will be printed?
let count = 0; function increment() { count++; } increment(); console.log(count);
Variables declared with let at global scope can be accessed and changed inside functions.
The variable count is declared globally with let. The function increment increases it by 1. So after calling increment(), count becomes 1.
Analyze this code snippet:
var a = 1;
function outer() {
var a = 2;
function inner() {
a = 3;
}
inner();
console.log(a);
}
outer();
console.log(a);What will be printed to the console?
var a = 1; function outer() { var a = 2; function inner() { a = 3; } inner(); console.log(a); } outer(); console.log(a);
Remember that inner changes the a in outer's scope, not the global a.
The variable a inside outer is initially 2. The inner function changes this a to 3. So console.log(a) inside outer prints 3. The global a remains 1, so the last console.log(a) prints 1.