Help_Steve_Code
Help_Steve_Code

Reputation: 97

Javascript While Loop Error with User Input

I am just beginning with JS and am having trouble with scope and executing code in similar style as I would with Python. I have started learning JS on Codecademy and have just begun my first project.

My code for the project is below:

//////////////////////////
// R U Hungry Console App
/////////////////////////

// Step 1: Load in Necessary Modules
////////////////////////////////////

// add in the prompt-sync module 
// allows to take in and display users name
const prompt = require('prompt-sync')();

// load in fs module
// allows reading in from text files
const fs = require("fs");

// load open module 
//allows the opening of webpages
const open = require('open');

// Step 2: Create a menu object 
///////////////////////////////

const menu = {
    starters: [],
    mains: [],
    desserts: []
}

// Step 3 Create a factory function to update the Menu object
/////////////////////////////////////////////////////////////

const menuUpdate = (course,dishName,dishLink) => {
    if (course.toLowerCase() === 'starter'){
        let newItem = {dish: dishName, link: dishLink};
        menu.starters.push(newItem);
    } else if (course.toLowerCase() === 'main'){
        let newItem = {dish: dishName, link: dishLink};
        menu.mains.push(newItem);
    } else if (course.toLowerCase() === 'dessert'){
        let newItem = {dish: dishName, link: dishLink};
        menu.desserts.push(newItem);
    } else {
        console.log('You did not enter a valid course.\nCould not update menu');
    }
}

// Step 4: Read in text files of scraped web data
/////////////////////////////////////////////////

const dishes = [menu.starters,menu.mains,menu.desserts];
const filesToRead = ['starters.txt','mains.txt','desserts.txt']; 

function addFiles(course,file){
    const text = fs.readFileSync(`./menu_files/${file}`);
    const textByLine = text.toString().split("\n");
    for (const line of textByLine){
        course.push(line);
    }
}

addFiles(dishes[0],filesToRead[0]);
addFiles(dishes[1],filesToRead[1]);
addFiles(dishes[2],filesToRead[2]);

// Step 5: Put it all together
//////////////////////////////

console.log('\n\nFeeling hungry and can\'t decide what to eat? You have come to the right place.')
const name = prompt('What is your name? ');
console.log(`\nWelcome, ${name}!\nWould you like to be:\n1.Presented With a Menu\n2.Add a Dish to the Menu`);

let userChoice;

while (true){
    userChoice = prompt('\nEnter 1 to get a Menu\nEnter 2 to add a Menu Item\nEnter 3 to exit R U Hungry ');

    if (userChoice.trim() === 1){
        const starterSelector = Math.floor(Math.random() * menu.starters.length);
        const mainSelector = Math.floor(Math.random() * menu.mains.length);
        const dessertSelector = Math.floor(Math.random() * menu.desserts.length);

        let starterDish = menu.starters[starterSelector][0];
        let starterRecipe = menu.starters[starterSelector][1];
        let mainDish = menu.mains[mainsSelector][0];
        let mainRecipe = menu.mains[mainsSelector][1];
        let dessertDish = menu.desserts[dessertSelector][0];
        let dessertRecipe = menu.desserts[dessertSelector][1];

        console.log(`${name}, your Menu is as follows:\n`);
        console.log(`Starter: ${starterDish}`);
        console.log(`Main: ${mainDish}`);
        console.log(`Dessert: ${dessertDish}`);

        console.log('\nWe will direct you to recipes for your selected dishes');

         // opens the url in the default browser 
        open(starterRecipe);
        open(mainRecipe);
        open(dessertRecipe);
                
    } else if (userChoice.trim() === 2){
        
        let userCourse = prompt('Is your dish a Starter, Main or Dessert?  ');
        let userDishName = prompt('Great! Please tell me the name of your dish  ');
        let userDishLink = prompt('Please provide the link to the dish recipe ');

        menuUpdate = (userCourse,userDishName,userDishLink);

        console.log('Menu updated with your dish!');
        
    } else {
        console.log(`Goodbye, ${name}.`);
        break;
    }

    console.log('Would you like to perform another function?');
    
    
}

// End



I am having trouble with the while loop at the end. This part specifically:

let userChoice;

while (true){
    userChoice = prompt('\nEnter 1 to get a Menu\nEnter 2 to add a Menu Item\nEnter 3 to exit R U Hungry ');

    if (userChoice.trim() === 1){
        const starterSelector = Math.floor(Math.random() * menu.starters.length);
        const mainSelector = Math.floor(Math.random() * menu.mains.length);
        const dessertSelector = Math.floor(Math.random() * menu.desserts.length);

        let starterDish = menu.starters[starterSelector][0];
        let starterRecipe = menu.starters[starterSelector][1];
        let mainDish = menu.mains[mainsSelector][0];
        let mainRecipe = menu.mains[mainsSelector][1];
        let dessertDish = menu.desserts[dessertSelector][0];
        let dessertRecipe = menu.desserts[dessertSelector][1];

        console.log(`${name}, your Menu is as follows:\n`);
        console.log(`Starter: ${starterDish}`);
        console.log(`Main: ${mainDish}`);
        console.log(`Dessert: ${dessertDish}`);

        console.log('\nWe will direct you to recipes for your selected dishes');

         // opens the url in the default browser 
        open(starterRecipe);
        open(mainRecipe);
        open(dessertRecipe);
                
    } else if (userChoice.trim() === 2){
        
        let userCourse = prompt('Is your dish a Starter, Main or Dessert?  ');
        let userDishName = prompt('Great! Please tell me the name of your dish  ');
        let userDishLink = prompt('Please provide the link to the dish recipe ');

        menuUpdate = (userCourse,userDishName,userDishLink);

        console.log('Menu updated with your dish!');
        
    } else {
        console.log(`Goodbye, ${name}.`);
        break;
    }

    console.log('Would you like to perform another function?');
    
    
}

It keeps executing the code in the else block and then exiting the program.

In python I would have used something like this:

while (True):
    choice = input("What is your name? ")
    if choice.strip().lower() != 'john':
        print("Who are you?")
        break;
    elif choice choice.strip().lower() != 'shaun':
        print("Who are you?")
        break;
    else:
        print("Hi there, glad you aren't John or Shaun")
        continue
    
    


Stupid example but I just wanted to show how I could normally have achieved something like this before. Would anyone be able to explain what is incorrect?

I also struggle to understand the scope in JS. Is that perhaps the problem here? I am finding it difficult in some cases to apply my thinking from Python to JS. Any help would be appreciated. I am really wanting to learn.

Thanks!

Upvotes: 0

Views: 106

Answers (1)

icebug
icebug

Reputation: 303

Maybe as a starter you can you == rather than === as it would not match the type, also in your else if it seems you are calling function incorrectly, remove =.

Upvotes: 1

Related Questions