Daily JavaScript Quiz - 2024-04-20

  • Home /
  • Daily JavaScript Quiz - 2024-04-20

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:

  1. console.log(name);: This line tries to log the value of the name variable before it is declared. In JavaScript, variables declared with var are hoisted (moved to the top of their scope) and initialized with the value undefined. So, name exists but its value is undefined.

  2. console.log(age);: This line tries to log the value of the age variable before it is declared. However, variables declared with let or const are not hoisted, and accessing them before declaration results in a ReferenceError. So, this line will throw an error.

  3. var name = 'Lydia';: Here, the variable name is assigned the value 'Lydia'. Since var is function-scoped, name is scoped to the entire sayHi function.

  4. let age = 21;: This line declares a variable age with the value 21. let is block-scoped, so age is scoped to the block in which it’s declared, which in this case is the sayHi 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.

Javascript Quizzes