Search code examples
javascripthtmlarrayspush

how to append on to this array with javascript


when you say new it should add the item you enter to the todo list and when I call list it should give me the list but the quit works and it quits the program if you have any advice can you please tell me how to fix this problem thank you in advance

window.setTimeout(function() {
    while(true){
        var rep = prompt("what ya wanna do?");
        var list = [];

        if(rep === "new"){
            var newItem = prompt("whacha wanna add?")
            list.push(newItem);
        }

        if(rep === "list"){
            alert(list)
        }
    
        if(rep === "quit"){
            break;
        }
    }
}, 500);
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="ps3.js"></script>
</head>
<body>
    <h1>Todo List</h1>
    <ul>
        <li>"new" - Add A Todo</li>
        <li>"list" - Veiw All Todos</li>
        <li>"quit" - Quit Applet</li>
    </ul>
</body>
</html>


Solution

  • Declare variable var list = []; outside the while loop

    Working example

    window.setTimeout(function() {
            var list = [];
        while(true){
            var rep = prompt("what ya wanna do?");
    
            if(rep === "new"){
                var newItem = prompt("whacha wanna add?")
                list.push(newItem);
            }
    
            if(rep === "list"){
                alert(list)
            }
        
            if(rep === "quit"){
                break;
            }
        }
    }, 500);
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
        <script src="ps3.js"></script>
    </head>
    <body>
        <h1>Todo List</h1>
        <ul>
            <li>"new" - Add A Todo</li>
            <li>"list" - Veiw All Todos</li>
            <li>"quit" - Quit Applet</li>
        </ul>
    </body>
    </html>