0

OK so I fixed my last error with the DIV and all..

OK so at the very top of my javascript file... I have

$(function() {
     var games = new Array(); // games array
});

and then in a new function I have: var gamesLgth = games.length;

but when I run it, I get this: Uncaught ReferenceError: games is not defined

When I weird because I initalized it at the very beginning...

6
  • "and then in a new function I have..." that is probably the issue; when you define a variable with var, it will only be available to the current function. Commented Oct 21, 2011 at 7:11
  • See this one: stackoverflow.com/questions/851138/… Commented Oct 21, 2011 at 7:12
  • Please show the code include new function. Commented Oct 21, 2011 at 7:12
  • See this one: stackoverflow.com/questions/851138/… Commented Oct 21, 2011 at 7:12
  • You can create a new array with just two characters: var games = [];. Commented Oct 21, 2011 at 7:14

2 Answers 2

0

games is out of scope. You need to store it somewhere such that your other function can access it.

For example, this will make your variable global.

var games;
$(function() {
    games = new Array(); // games array
});

$(function() {
   var gamesLgth = games.length;
   console.log(gamesLgth);
});
Sign up to request clarification or add additional context in comments.

1 Comment

OF COURSE! I remember this in Java with global variables and such. It is coming back to me.! Thank you. I got it. I got it. Muchas gracias, senor.
0

By declaring that variable within a function you have scoped the variable to that function, which means that that variable games is only available within that function.

$(function() {
     var games = new Array(); // games array

     ...


     var gamesLength = games.length; // works fine
});

But this following example will not:

$(function() {
     var games = new Array(); // games array
});

$(function() {
     var gamesLength = games.length; // won't work - im in a different scope
});

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.