Array shows undefined in the console.log even though it has a global scope

527 Views Asked by At
$(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.

0

There are 0 best solutions below