0

I am new to programming.

I know that I could use functions and loops to keep from repeating this code, but I need help. Anyone?

var questions = 3;    
var questionsCount = ' [' + questions + ' questions left]';    
var adjective = prompt('Please type an adjective' + questionsCount);   
questions -= 1;   
questionsCount = ' [' + questions + ' questions left]';
var verb = prompt('Please type a verb' + questionsCount);
questions -= 1;
questionsCount = ' [' + questions + ' questions left]';
var noun = prompt('Please type a noun' + questionsCount);
alert('All done. Ready for the message?');
var sentence = "There once was a " + adjective;
sentence += ' programmer who wanted to use JavaScript to ' + verb;
sentence += ' the ' + noun + '.';
document.write(sentence);
Kishan Viramgama
  • 713
  • 1
  • 9
  • 18
cono_mich
  • 13
  • 2
  • 2
    Try writing a `for` loop. Also, don't use `document.write()`. https://stackoverflow.com/a/802943/362536 If you're in a class and they're teaching you to use `document.write()`, you should be very suspicious of pretty much everything they're telling you. – Brad Sep 26 '19 at 04:03

1 Answers1

3

I'd use a string template which contains, eg, {{noun}} to be replaced with a noun, which uses a regular expression to prompt the user for replacements to make:

const template = 'There once was a {{adjective}} programmer who wanted to use JavaScript to {{verb}} the {{noun}}.';
let questions = 3;
const result = template.replace(
  /{{(.*?)}}/g,
  (_, typeOfSpeechNeeded) => prompt(`Please type a ${typeOfSpeechNeeded}, ${questions--} question(s) left`)
);

console.log(result);

The regular expression

{{(.*?)}}

matches {{, followed by some characters, followed by }}, where those characters are put into a capturing group - this allows the .replace to examine the capturing group to determine what typeOfSpeechNeeded to display in the prompt.

The /g in the regular expression makes it global, which replaces all matches, not just the first match.

The backtick string is just a more readable way of interpolating strings:

prompt(`Please type a ${typeOfSpeechNeeded}, ${questions--} question(s) left`)

is equivalent to

prompt('Please type a ' + typeOfSpeechNeeded + ', ' + questions-- + ' question(s) left')
CertainPerformance
  • 260,466
  • 31
  • 181
  • 209
  • 2
    This is the right answer in my opinion, but this person is just getting started with JavaScript. Could you take the time to explain what replace is doing, what regex is, how your anonymous callback function works, and how the backtick string interpolation works? – Brad Sep 26 '19 at 04:06
  • Seriously--thank you for breaking it down for me. Much appreciated. – cono_mich Sep 26 '19 at 04:18
  • Awesome, doing it now! Didn't realize. Thanks @CertainPerformance – cono_mich Sep 28 '19 at 04:29