2

I have the following:

var movie;

var myMovies = ['Bones', 'Psych', 'Big Bang Theory', 'Mad Men', 
'Breaking Bad', 'Modern Family', 'Game of Thrones', 'Dexter','Bones', 'Psych', 'Big Bang Theory', 'Mad Men', 
'Breaking Bad', 'Modern Family', 'Game of Thrones', 'Dexter','Bones', 'Psych', 'Big Bang Theory', 'Mad Men', 
'Breaking Bad', 'Modern Family', 'Game of Thrones', 'Dexter'];

function generateMovies () {
  var movie = myMovies[Math.floor(Math.random() * myMovies.length)];
}


function displayMovie() {
  generateMovies();
  console.log(movie);
  $('body').text(movie);

  setTimeout(function(){
    displayMovie();
},1000);
}

displayMovie();

I would like to generate a different movie name and show them on the screen. Seems to be straight forward but obviously not! Seems like may variable is undefined.

Thanks!

Fiddle: https://jsfiddle.net/4ggwva4f/8/

3 Answers 3

2

You are declaring the variable movie inside the function, so you are not assigning the value to the global variable.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, that was the problem!
Yeah, it would help to set the variable that you'll be using. :D
1

Just remove var in your generateMovies function.

function generateMovies () {
  movie = myMovies[Math.floor(Math.random() * myMovies.length)];
}

Basically, you're declaring movie first at the start of your script, then again within your generateMovies function, so movies is not being returned into your global scope.

Comments

0

As the other guys mentioned, you have a scope problem. Also, you don't really need the global movie variable, you could change your code to return the expected value like this:

var myMovies = ['Bones', 'Psych', 'Big Bang Theory', 'Mad Men', 
'Breaking Bad', 'Modern Family', 'Game of Thrones', 'Dexter','Bones', 'Psych', 'Big Bang Theory', 'Mad Men', 
'Breaking Bad', 'Modern Family', 'Game of Thrones', 'Dexter','Bones', 'Psych', 'Big Bang Theory', 'Mad Men', 
'Breaking Bad', 'Modern Family', 'Game of Thrones', 'Dexter'];

function generateMovies () {
  return myMovies[Math.floor(Math.random() * myMovies.length)];
}

function displayMovie() {
  var movie = generateMovies();
  console.log(movie);
  $('body').text(movie);

  setTimeout(function(){
    displayMovie();
},1000);
}

displayMovie();

Or if you don't really need to do the console.log just: $('body').text(generateMovies())

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.