Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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.