There are two variables in which data is written:

let finance = +prompt('Ваш бюджет?'); while (finance === "" || isNaN(finance) || finance === null) { let finance = prompt('Ваш бюджет?'); } let name = prompt('Название вашего магазина?'); while (name == "" || name == null) { let name = prompt('Название вашего магазина?'); } 

When entered into the first variable, everything is recorded without problems. The second one, too, but if, when entering into the second variable, first press Cancel or Ok and then enter without errors, it loops and the script does not go further, although the first variable works fine. What is the problem?

  • four
    Remove the let inside the loop. - Stepan Kasyanenko
  • Can you explain why in the first one everything works okay, but in the second variable you need to remove the let? - Darkhan Urustimov
  • one
    @ Darkhan Urustimov 1. The code with finance loops in no less for the same reason. 2. You finance result in a number immediately (with the help of a unary plus), therefore comparisons with finance === "" and finance === null meaningless (if you enter and cancel, you have 0 ). - Regent
  • one
    @Regent, Yes, I even started to write an answer about it, but then I pereklinilo something :) - Grundy
  • @Grundy seems to me that this is not a duplicate. Here the problem is not with window.name , but with the scope of the variables. - Stepan Kasyanenko

1 answer 1

The problem is in excess let .

Since using this keyword, the scope is limited to a block, not a function - the value entered inside the loop does not coincide with what is checked in the condition.


Why not get hung up in the first case?

Since the unary operator is used + - the result of the prompt immediately reduced to a number.

The reduction to the number works according to the table in which it is noted that in the case of null result is +0 , an empty string, or a string of only spaces will be reduced to 0 .

Therefore, when you click cancel or enter an empty line, none of the conditions are met.

It should be noted that when entering a string that cannot be brought to a number in the first case, there will also be a looping, since the result of the cast in this case will be NaN .

  • @Regent, Added - Grundy