Javascript return to top of code or restart it

Viewed 29

Hi I´m looking for a way to restart my code or return to the top of it to let it run again. Is there a method or code I can look up and integrad it in my code?? As you can see I have an if statement with an input as a condition. I would like to restart my code if we type reset in the console.

//wiederholung von buchstaben message
//when entry is wrong or repeated --> list previous wrong letters
//Win message 
//difficulty

const constants = require('./constants');
// In node.js: install a prompt library by running: `npm install prompt-sync` in the current folder
const prompt = require("prompt-sync")();

// Here you see an example how to get your
// constants from constants.js
/*for(let figure of constants.HANGMAN_PICS)
{
   console.log(figure);
}
*/
let answer = [];
let count = 0;
let usedLetters = [];

var word = constants.WORDS_TO_GUESS[Math.floor(Math.random()*constants.WORDS_TO_GUESS.length)];

for(let i=0; i < word.length; i++) {
   answer[i]="_";
}

console.log(answer.join(" "));

for(;answer!==word;) {

input = prompt (`Finde das Wort.`).toLocaleLowerCase();

if(word.toLocaleLowerCase().includes(input)) {
   for(let i=0; i < word.length; i++) {
   if (word[i].toLocaleLowerCase() === input) {
   console.clear();
   answer[i]=word[i];
   console.log("Good Job!");
   console.log(constants.HANGMAN_PICS[count]);
} 

}
}else if(!word.includes(input)){
   console.clear();
   console.log("Falsche Eingabe!");
   console.log("Hello");
   count++;
   console.log(constants.HANGMAN_PICS[count]); 
   if(usedLetters.includes(input)){
      console.log("Erneute Falscheingabe");
      console.log(usedLetters);
   }
 usedLetters.push(input);
}

if(input === "quit"){
   return;
}
else{

console.log(answer.join(" "));

}
}
// how to use the prompt - e.g.:
// const name = prompt('What is your name?');

1 Answers

Wrap the code that executes the logic of your game inside of a function. Let's call this function game.

Unlike the code in your snippet, the code inside game doesn't run untill we invoke the function. To run the game, call the function with game(). The logic will now start running.

A function is able to call itself, meaning that you can repeat the logic again. This is called recursion.

In the snippet below game logic is defined inside of the game function. The function is then called which starts the logic. Inside the game we're asked to repeat the game. If true is the result from the confirm prompt, then game is called again, starting the logic from the top.

function game() {
  const name = prompt('What is your name?');
  const repeat = confirm(`Hi ${name}, do you want to ask again?`);
  
  if (repeat === true) {
    game();
  }
}

game();

Related