0
$(document).ready(function() {
    var arr = [], input;

    $('#add').click(function() {
        input = $('#input').val();
        arr.push(input);

    });
    console.log(arr);
});

The above code show nothing in the console however when I move the console.log(arr); line just under arr.push(input); line than suddenly it shows the array. What is going on here?

Also here is the html code if it helps.

<form action="#">
    <input type="text" id="input">
    <input type="submit" value="Add" id="add">
    <input type="submit" value="Display" id="display">
</form>

I need the array to be available outside the click function so that I can use it inside the display click function to display the array on the page.

This question has got nothing to do with asynchronous whatever please don't mark it as duplicate. It is a simple question and needs a simple answer.

SomeDude
  • 23
  • 6
  • I'm not sure that this is a duplicate. I think the answer to the question is that the array is empty when it is being displayed and the OP's `console.log` renders empty arrays with no characters at all. (I see `[]` in Chrome though.) By moving the logging inside the callback the OP then has an array with something in it so it becomes visible. In either case the array _is_ shown, it's just that at first, it's empty. – Ray Toal Jan 02 '17 at 10:20
  • Try to console inside the click event. – Amit Jamwal Jan 02 '17 at 10:25
  • @AmitJamwal when I try it inside the click event it works perfectly, however i need it to be available outside the click event. – SomeDude Jan 02 '17 at 10:28
  • $(document).ready(function() { var arr = [], input; $('#add').click(function() { input = $('#input').val(); arr.push(input); test(); }); function test(){ console.log(arr); } }); You need some event to get value of "arr". As console outside the click event is only called when document.ready() is called. Hope this helps you. – Amit Jamwal Jan 02 '17 at 10:34
  • Oh my goodness dude you are a genius, you should post your answer as the answer to my question so I can pick as the correct answer. Also than you so much for you time both you @AmitJamwal – SomeDude Jan 02 '17 at 10:38
  • Your question is marked as duplicate. – Amit Jamwal Jan 02 '17 at 10:41

0 Answers0