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,660 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,660 Points

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

Antti Lylander
Antti Lylander
9,660 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 :)