Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

javascript: Why does this code result in an error.?

I'm not trying to fix it. I just want to know why it results in the error:

ReferenceError: prisoner_2 is not defined

The code:

function prison(){

prisoner_1='I have escaped';

var prisoner_2='I am locked in';

};

prison();

console.log(prisoner_1);

console.log(prisoner_2);

2 Answers

Relevance
  • Anonymous
    6 years ago
    Favorite Answer

    Because it is declared within the function with a VAR which means it is only seen within the function - it is locked in.

    Compare with...

    function prison(){

    prisoner_1='I have escaped';

    var prisoner_2='I am locked in';

    alert(prisoner_2)

    };

    prison();

    prisoner_2 = "I escaped too!"

    console.log(prisoner_1);

    console.log(prisoner_2);

  • 6 years ago

    Because prisoner_2 is declared in function prison() and so is only in scope for that function.

    You could make it global or, better, declare it in the main body and pass it to the function as argument.

Still have questions? Get your answers by asking now.