Scope Quiz

Hi! I am doing the Scope quiz however every time is declaring a function in the code showing is with “const” for example:

What will be the output of this code?

let sayHello = ‘Hi there’;
const sayGoodbye = ‘Goodbye’;

const speakItalian = () => {

  • sayHello = ‘Ciao!’;*
  • console.log(sayHello);*
  • console.log(sayGoodbye);*
    };

speakItalian();

choose:

a) Hi there
Goodbye

b) Ciao!
Goodbye

c) Ciao!
ReferenceError: variable not defined.

Right answer showing b
I think this is an error but if not can someone clarify?

Hi there!

Let’s run that code in a REPL and see what we get, shall we?

image

As you can see, the code produces the result described in answer B.

This is because, whilst sayHello is initialized with a value of “Hi there”, we reassign it inside of the speakItalian function so it has the value Ciao!.

The sayHello variable is in the global scope, and since we aren’t using the let keyword inside of speakItalian we are modifying the global variable, not creating a new block-scoped variable also called sayHello.

If we wanted to create a new block-scoped sayHello variable, which would only exist within our speakItalian function, we need the let keyword which the quiz question doesn’t use. It would look like this:

image

Hope that clears it up, but if not please let us know. :slight_smile: