2

I simply want to access the value of array status from another function. However, the alert is giving me value as undefined. Here's my code:

Test.php:

<html>
    <body>
        <script>
            var status=[];
            status[0]='1';

            calculateInput();

            function calculateInput(){
                alert(status[0]);
            }
        </script>
    </body>
</html>
7
  • Where are you calling calculateInput() Commented Mar 23, 2014 at 18:47
  • Maybe clarify type="text/javascript" in the script-tag? Not sure that that's the problem... Commented Mar 23, 2014 at 18:48
  • I even tried to remove var initilization for status as i had read somewhere to make array global you have to use status=[]; but still value comes as undefined Commented Mar 23, 2014 at 18:50
  • Interestingly, your code works just fine in a JSFiddle: jsfiddle.net/A7Z3N (Firefox, at least.) Commented Mar 23, 2014 at 18:51
  • In the javascript itself there is function call for calculateInput Commented Mar 23, 2014 at 18:51

2 Answers 2

3

You are colliding with window.status:

function calculateInput () {
    alert( status === window.status ); // true
}

To avoid this, rename your array or get out of the global scope:

(function IIFE () {

    var status = [];

    status[0] = "1";

    calculateInput();

    function calculateInput () {
        alert( status[0] );
    }

}());
Sign up to request clarification or add additional context in comments.

3 Comments

actually I also want to use the array in another function. So I have to use global.
@DikshayPoojary You don't need to put it in the global scope. If you still want to, namespace it or given it a different name.
JavaScript is great, you can overwrite undefined "constant", but window.status is protected... :)
1

Change your variable name from status to something else

ex.

<html>
    <body>
        <script>
            var mystatus=[];
            mystatus[0]='1';

            calculateInput();

            function calculateInput(){
                alert(mystatus[0]);
            }
        </script>
    </body>
</html>

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.