Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Basics (Retired) Storing and Tracking Information with Variables Capturing Visitor Input

david mchale
david mchale
1,434 Points

Name still returns

var userName = function userName(){

        var name = prompt("What is your name");
        if(name === "David")
                alert("Please choose another name");
                name = prompt("What is your name");

                return name;

};

var result = userName(); document.write(result);

I don't think having to write name = prompt("What is your name"); twice is correct. Im sure there is an easier way for this work ....

1 Answer

Leandro Botella Penalva
Leandro Botella Penalva
17,618 Points

Hi David,

A better way to ask the name until the name is not equal as "David" would be using the do-while loop.

Here is the function using it:

var userName = function userName() {
    do {
        name = prompt("What is your name");
        if(name === "David") {
            alert("Please choose another name");
        }
    } while (name === "David");
    return name;
};

In this case the content of the do block will be repeated every time the while condition is true.