Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

Check if an array is empty or exists

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" />');
else{
$('#prev_image').attr('disabled', 'true');
$('#next_image').attr('disabled', 'true');
alert('Please get new image');
var image_array = [];
}


UPDATE Before loading html, I have something like this:

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

3 Answers

aashaykumar

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
}
sandhya6gczb
How about (ECMA 5.1):

if(Array.isArray(image_array) && image_array.length){
// array exists and is not empty
}
RoliMishra
As optional chaining proposal reached stage 4 and is getting wider support, there is a very elegant way to do this

if(image_array?.length){

// image_array is defined and has at least one element

}

Login / Signup to Answer the Question.