Yahoo Clever wird am 4. Mai 2021 (Eastern Time, Zeitzone US-Ostküste) eingestellt. Ab dem 20. April 2021 (Eastern Time) ist die Website von Yahoo Clever nur noch im reinen Lesemodus verfügbar. Andere Yahoo Produkte oder Dienste oder Ihr Yahoo Account sind von diesen Änderungen nicht betroffen. Auf dieser Hilfeseite finden Sie weitere Informationen zur Einstellung von Yahoo Clever und dazu, wie Sie Ihre Daten herunterladen.

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 Antworten

Relevanz
  • Anonym
    vor 6 Jahren
    Beste Antwort

    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);

  • vor 6 Jahren

    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.

Haben Sie noch Fragen? Jetzt beantworten lassen.