Silly story generator review

Hello!

I just finished my Silly story generator and I’d like someone to have a look at it. Thanks a lot!

var customName = document.getElementById(‘customname’);
var randomize = document.querySelector(’.randomize’);
var story = document.querySelector(’.story’);

function randomValueFromArray(array){
return array[Math.floor(Math.random()*array.length)];
}

var storyText = "It was 94 farenheit outside, so " + insertX + "went for a walk. When they got to " + insertY + ", they stared in horror for a few moments, then " + insertZ + “. Bob saw the whole thing, but he was not surprised — :insertx: weighs 300 pounds, and it was a hot day.”;

var insertX = ["Willy the Goblin ", "Big Daddy ", "Father Christmas "];
var insertY = ["the soup kitchen ", "Disneyland ", "the White House "];
var insertZ = ["spontaneously combusted ", "melted into a puddle on the sidewalk ", "turned into a slug and crawled away "];

randomize.addEventListener(‘click’, result);

function result() {

var newStory = storyText;
var itemX = randomValueFromArray(insertX);
var itemY = randomValueFromArray(insertY);
var itemZ = randomValueFromArray(insertZ);

if(customName.value !== ‘’) {
var name = customName.value;
}

if(document.getElementById(“uk”).checked) {
var weight = Math.round(300 / 7) + " kgs";
var temperature = Math.round(94 / 2.8) + " centigrade";
} else if(document.getElementById(“us”).checked) {
var weight = Math.round(300) + " stone";
var temperature = Math.round(94) + " fahrenheit";
}

story.textContent = "It was " + temperature + " farenheit outside, so " + itemX + " went for a walk. When they got to " + itemY + ", they stared in horror for a few moments, then " + itemZ + " " + name + " saw the whole thing, but he was not surprised — " + itemX + weight + “, and it was a hot day.”;
story.style.visibility = ‘visible’;
}

Hi there!

I just tested your code, and it looks like it works fine - great work!

the only thing I noticed was that my JS linter brought up some errors saying that the name, weight, and temperature variables are used out of scope. This is because you declare them (e.g. var ...) inside the inner blocks of the result function, then try to use them in the final section at the bottom.

To fix this, you could define them at the start of the function (e.g. var name, weight, function;), and then give them values when required without redefining them (e.g. name = ..., without the var keyword)

Also have a look at my version, with solves it slightly differently: https://github.com/mdn/learning-area/blob/master/javascript/introduction-to-js-1/assessment-finished/main.js

Hi Chris,

Thanks for looking at it and thanks for sharing your solution - it’s really helpful :slight_smile: