Daily Quiz - 2024-04-20
function sayHi() {
console.log(name);
console.log(age);
var name = 'Lydia';
let age = 21;
}
sayHi();
Lydia and undefined
Lydia and ReferenceError
ReferenceError and 21
undefined and ReferenceError
The answer is Option 4
This code defines a function sayHi
that tries to log the values of name
and age
variables, and then declares two variables name
with var
and age
with let
within the function.
Here’s what happens when sayHi()
is called:
console.log(name);
: This line tries to log the value of thename
variable before it is declared. In JavaScript, variables declared withvar
are hoisted (moved to the top of their scope) and initialized with the valueundefined
. So,name
exists but its value isundefined
.console.log(age);
: This line tries to log the value of theage
variable before it is declared. However, variables declared withlet
orconst
are not hoisted, and accessing them before declaration results in a ReferenceError. So, this line will throw an error.var name = 'Lydia';
: Here, the variablename
is assigned the value'Lydia'
. Sincevar
is function-scoped,name
is scoped to the entiresayHi
function.let age = 21;
: This line declares a variableage
with the value21
.let
is block-scoped, soage
is scoped to the block in which it’s declared, which in this case is thesayHi
function.
When sayHi()
is invoked, it logs undefined
for name
and throws a ReferenceError for age
, and then it assigns 'Lydia'
to name
. The let
declaration for age
is not reached due to the error. So, the output would be:
undefined
ReferenceError: age is not defined
In general, it’s good practice to declare variables at the top of their scope to avoid confusion and unexpected behavior like this.