This question has already been answered:

There is a code

var isKeyPressed=0; document.onkeydown = function (){ isKeyPressed=1; }; if (isKeyPressed) alert("Привет!"); 

Why doesn’t alert output when I press the button? Those. Why is the value of the isKeyPressed variable not changed, not passed from the function? (I can understand that the alert can be output by inserting it inside a function. The question is about the variable)

Reported as a duplicate by participants of Pavel Mayorov , cheops , aleksandr barakin , user194374, Nick Volynkin 1 Aug '16 at 3:57 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

    1 answer 1

    At the time of execution of the alert, judging by this code, the variable = 0. Read the comments on the code below "in terms of the browser (the one who executes the code)":

     //первый шаг: установили переменную в значение "0", все ясно. var isKeyPressed=0; //второй шаг: так, когда нажмут клавишу выполню эту функцию. Ок. А пока даже заглядывать туда не буду. document.onkeydown = function (){ //четвертый шаг (в неизвестный момент времени после остальных): ага, клавишу нажали, присваиваем переменной значение "1". isKeyPressed=1; }; //третий шаг: так, чему там равна переменная? ага, "0". Значит не заходим сюда. if (isKeyPressed) alert("Привет!"); 

    You have the same alert does not fall out when you press a key, but immediately when the page loads. A variable in 1 is set only after pressing.