Javascript – Check if an array is empty or exists


When the page is loading for the first time, I need to check if there is an image in image_array and load the last image.

Otherwise, I disable the preview buttons, alert the user to push new image button and create an empty array to put the images;

The problem is that image_array in the else fires all time. If an array exists – it just overrides it, but alert doesn't work.

if(image_array.length > 0)
    $('#images').append('<img src="'+image_array[image_array.length-1]+'" class="images" id="1" />');
    $('#prev_image').attr('disabled', 'true');
    $('#next_image').attr('disabled', 'true');
    alert('Please get new image');
    var image_array = [];

Before loading html, I have something like this:

<?php if(count($images) != 0): ?>
<script type="text/javascript">
    <?php echo "image_array = ".json_encode($images);?>
<?php endif; ?>

Best Solution

if (typeof image_array !== 'undefined' && image_array.length > 0) {
    // the array is defined and has at least one element

Your problem may be happening due to a mix of implicit global variables and variable hoisting. Make sure you use var whenever declaring a variable:

<?php echo "var image_array = ".json_encode($images);?>
// add var  ^^^ here

And then make sure you never accidently redeclare that variable later:

else {
    image_array = []; // no var here