2

I have a small javascript which has a globally declared array. The values for that array are filled inside the function foo() as given below:

<html>
<head></head>
<body>
 <script>
    var myArray = [];

  function foo() {
     var j = 5;
      for (var i = 0; i < j; i++) {
         myArray.push(i+1);
       }  
    }

  function bar() {
   alert(myArray);
   }

 </script>
</body>
</html>

When I trying to access that array in another javascript function bar(), the values of array are null. How can I fix this?

4
  • call foo() before bar() Commented Jun 24, 2014 at 6:53
  • Not working @Harpreet Singh jsfiddle.net/U5L9w Commented Jun 24, 2014 at 6:56
  • Its working. Do i need to show a screen shot of mine in a comment? Commented Jun 24, 2014 at 7:01
  • But the global variable should be accessible anywhere inside the script without calling the function right? Commented Jun 24, 2014 at 7:07

2 Answers 2

1

you have defined the function but never called it.

Try calling foo() and bar() like this

  var myArray = [];

function foo() {
   var j = 5;
    for (var i = 0; i < j; i++) {
       myArray.push(i+1);
     }  
  }

function bar() {
  alert(myArray);
 }

 foo();

 bar();

JSFiddle

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

5 Comments

@mpsbhat you're not understanding. simply defining a method/function wont execute, you need to call it. in your case see this JSFiddle
But the global variable should be accessible anywhere inside the script without calling the function right @Navin?
@mpsbhat yes, that's the reason you're getting empty array in alert, if not global then you'd get myArray is undefined error.
So once a global variable declared and if a value is assigned to it inside a function, then that value should present until the another value is assigned to it?
see this JSFiddle hope you'll understand now.
1

If you are going to call bar() directly then.

<script>

  function foo(myArray) {

          var j = 5;

          for (var i = 0; i < j; i++) {

              myArray.push(i+1);

          }  

         return myArray;
  }

  function bar() 
  {
       alert(foo([]));
  }

  bar();  

// or

  alert(foo([]));

 </script>

Try to avoid as many global variables as you can,

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.