Challenge understanding the syntax for the "Silly story generator" assessment

This assessment has been giving me a real challenge, so much so that I’ve decided to look at a solution and try to understand how it works line by line, but there are still some things I am not understanding.

let newStory = newStory.replace(:insertx:, xItem);
let newStory = newStory.replace(:inserty:, yItem);
let newStory = newStory.replace(:insertz:, zItem);
let newStory = newStory.replace(:insertx:, xItem);

I don’t understand how its possible to have three different variables with the same name (newStory). And I’m also not getting why the line with the “xItem” variable has to be repeated.

Hi @Xavier_Reynolds and welcome to the community :wave:

You are right in your feeling that different variables can’t have the same name. So what is going on here?
It is always the same variable which we are updating on every line. After replacing a substring the replace function returns the updated string. For a better understanding we could rename the variables:

let newStoryWithUpdate1 = newStory.replace(':insertx:', xItem);
let newStoryWithUpdate2 = newStoryWithUpdate1.replace(':inserty:', yItem);
let newStoryWithUpdate3 = newStoryWithUpdate2.replace(':insertz:', zItem);
let newStoryWithUpdate4 = newStoryWithUpdate3.replace(':insertx:', xItem);
/* After the replacements we reassign the updated string to the original variable */
let newStory = newStoryWithUpdate4;

Since replace returns the updated string you could also chain all four replace functions. This version isn’t very readable though:

let newStory = newStory.replace(':insertx:', xItem).replace(':inserty:', yItem).replace(':insertz:', zItem).replace(':insertx:', xItem);

For your second question:
When using replace with just a simple string to be replaced, it will only replace the first match. Since we have two :insertx: in our story we need to call replace twice. To do a global search and replace a regular expression has to be used. (This is a rather complicated topic so I wouldn’t bother for now.)

As a general note:
Learning a programming language is sometimes hard but very satisfying when it finally ‘clicks’. I think it is a great idea to read others code and trying to understand it :+1:

If you have any other questions I’m happy to help :slightly_smiling_face:

Have a nice day!
Michael

Thanks for the help and the positive reinforcement Michael. Have a nice day yourself.

1 Like

I have a small addition to my comment about replace. I totally forgot about the replaceAll function :smile:
It works exactly like replace but replaces all occurrences. That’s much easier than the mentioned regular expressions.