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 Loops, Arrays and Objects Tracking Multiple Items with Arrays Useful Array Methods

Timothy Harrington Bourne
Timothy Harrington Bourne
6,372 Points

What's wrong with my code? - Arrays

var inStock = ['mango','eggs','tofu','kale','bread','spinach', 'condoms']
var search;

function print(message) {
    document.write('<p>' + message + '</p>')
}

while (true) {
    search = prompt ("Search for a product in our store. Type 'list' to show all products available and type 'quit' to exit")
    if (search === 'quit') {
        break
    } else if(search === 'list') {
        print(inStock.join(', '))
    } else {
        if ( inStock.indexOf( search ) > -1 ) {
            print('yes, we have ' + search + ' in the store')
        } else {
            (search + ' is not in the store')
        }
    }
}

The prompt wont show text on the webpage when I search for something that's in the array.

Can you format the code so it can be read. Use three back ticks for code.

4 Answers

Thanks. I didn't get the problem as I was using Firefox, but now I'm aware of it.

In JavaScript, every statement should end with a semicolon, but you have only ended the second line with one. Also, on the last else statement, you have missed out the function name 'print'.

Antti Lylander
Antti Lylander
9,674 Points

Fix issues that Robert mentioned and it still won't work because nowadays browsers do not print anything until you exit the loop.

Is this a security thing or an optimisation thing? Not come across it before.

Antti Lylander
Antti Lylander
9,674 Points

I have no idea why they have changed browsers behavior about this.

Antti Lylander
Antti Lylander
9,674 Points

It will print when you close the prompt. It's just how the browsers work now. You can add break inside each if block. Then you just need to refresh the page in order to search next.

Don't worry about it too much. You will soon learn how to make this kind of page without a prompt, i.e. with input forms.

Timothy Harrington Bourne
Timothy Harrington Bourne
6,372 Points

Yeah, Im currently taking a break from all of this for a little while... Arrays are so confusing at this point of my study :/ Will revisit the code soon enough. Thank you for the input :)