The code does not work! Plz help!


#1

I dunno whats wrong with the code, to me it seems alright....Please explain why it does not work...When I run the code and the prompt comes up and I insert 0, it still shows "Did not loop!" Why so?
thanks

var soloLoop = function(x) {
while(x===0) {
console.log("Looped once!");
x===1;
};
console.log("Did not loop!")
};
soloLoop(prompt("choose either 0 or 1"));


#2

I guess the problem is that you pass a number generated by prompt to the function. In detail: Prompt always creates a string even if you enter 1 what prompt creates would be "1" and as === compares the value and the type "1" is not equal to 1. So you either need to be less strict and only compare the value by == or you need to use something like this:
https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/parseInt
to convert the string to a number.

Merry Christmas :christmas_tree:


#3

Thanks for your advice, I tried changing the numbers to strings, but still didnt work...what happens now is that the browser crashes! which means that the condition runs true...but it doesn't print anything, it just hangs the browser...
thanks, and Merry Christmas to you too


#4

Could you post the updated version of your code,pls?


#5

I simply put "" around the nmbers in the code, in order to make it into a string. But it still did not work!

var soloLoop = function(x) {
while(x===0) {
console.log("Looped once!");
x===1;
};
console.log("Did not loop!")
};
soloLoop(prompt("choose either 0 or 1"));

But I finally resolved the problem. I changed the script a bit and now it works...This is how I changed it further!

var myPrompt = prompt("choose Harry or Ron");

var soloLoop = function() {
while(myPrompt==="Harry") {
console.log("Looped twice!");
myPrompt = prompt("choose Harry or Ron")
};
console.log("Looped once!");
};
soloLoop();

This worked out perfect!! :smiley:


#6

lol I guess I copied the wrong old code in the first part on here