Daily Quiz - 2024-04-09
var a = 1
function output () {
var a = 2
}
console.log(a)
output()
console.log(a)
2, 1
2, 2
1, 1
1, 2
The answer is Option 3
var a = 1
: This line declares a variablea
in the global scope and assigns it the value1
.function output() { var a = 2; }
: This line defines a function namedoutput
, which declares a new variablea
with the value2
within its scope. This variablea
is local to the functionoutput
, and it doesn’t affect the global variablea
.console.log(a)
: Here, the value of the global variablea
is logged to the console. At this point, the value ofa
is1
, as it hasn’t been changed by the functionoutput
.output()
: This line calls theoutput
function, but since it doesn’t return any value, it doesn’t affect the global variablea
.console.log(a)
: Finally, the value of the global variablea
is logged again. It remains1
because the functionoutput
did not modify the global variablea
. Thea
inside the functionoutput
is a separate variable local to that function and does not affect the global scope.
So, the output of this code will be:
1
1
Because the function output
doesn’t change the global variable a
.