- Joined
- Dec 6, 2023
- Messages
- 1
- Reaction score
- 0
Hello everybody,
I am new to coding, and I am learning Javascript on my own. I have found the following mini-program and I don´t understand how the algorithm works.
let yourName;
do {
yourName = prompt("Who are you?");
} while (!yourName);
console.log(yourName);
This program will force you to enter a name. It will ask again and again until it gets something that is not an empty string.
Applying the ! operator will convert a value to Boolean type before negating it, and all strings except "" convert to true.
This means the loop continues going round until you provide a non-empty name.
Clearly the program works because I run it. However, I do not understand the logic of this while loop with the "logical NOT operator"
while (!yourName);
console.log(yourName);
When someone enters a (not empty) string value, the operator transforms it into a boolean and then negates it. Which means that in the end (!yourName) = false.
So my while loop seems to say:
"while the condition in the parentheses is false, print out yourName". What confuses me is that I believed that the condition in the while loop needs always to be truthy/true in order to take the action (print out in this case)
I was thinking that the logic is always
while (true) -----> do this action
I hope I clarified my point. Thank you in advance for this awesome forum and any help you can give me
Salva
I am new to coding, and I am learning Javascript on my own. I have found the following mini-program and I don´t understand how the algorithm works.
let yourName;
do {
yourName = prompt("Who are you?");
} while (!yourName);
console.log(yourName);
This program will force you to enter a name. It will ask again and again until it gets something that is not an empty string.
Applying the ! operator will convert a value to Boolean type before negating it, and all strings except "" convert to true.
This means the loop continues going round until you provide a non-empty name.
Clearly the program works because I run it. However, I do not understand the logic of this while loop with the "logical NOT operator"
while (!yourName);
console.log(yourName);
When someone enters a (not empty) string value, the operator transforms it into a boolean and then negates it. Which means that in the end (!yourName) = false.
So my while loop seems to say:
"while the condition in the parentheses is false, print out yourName". What confuses me is that I believed that the condition in the while loop needs always to be truthy/true in order to take the action (print out in this case)
I was thinking that the logic is always
while (true) -----> do this action
I hope I clarified my point. Thank you in advance for this awesome forum and any help you can give me
Salva