In this tutorial we will learn how to check if array is empty or null or undefined using javascript.
Here well will see all three conditions one by one.
Let's see examples -
<!DOCTYPE html>
<html>
<head>
<title>How to check if array is empty or null or undefined using javascript</title>
</head>
<body>
<script type="text/javascript">
var myArray = [1, 2, 3];
if (myArray && myArray.length > 0) {
alert('myArray is not empty.');
} else {
alert('myArray is empty.');
}
</script>
</body>
</html>
Output
<!DOCTYPE html>
<html>
<head>
<title>How to check if array is empty or null or undefined using javascript</title>
</head>
<body>
<script type="text/javascript">
var myArray = [];
if (myArray && myArray.length > 0) {
console.log('This array is not empty.');
} else {
alert('This array is empty.');
}
</script>
</body>
</html>
Output
<!DOCTYPE html>
<html>
<head>
<title>How to check if array is empty or null or undefined using javascript</title>
</head>
<body>
<script type="text/javascript">
var myArray = null;
if (myArray && myArray.length > 0) {
console.log('This array is not null.');
} else {
alert('This array is null.');
}
</script>
</body>
</html>
Output
<!DOCTYPE html>
<html>
<head>
<title>How to check if array is empty or null or undefined using javascript</title>
</head>
<body>
<script type="text/javascript">
var myArray = [1, 2, 3];
if (myArray && myArray.length > 0) {
alert('myArray is not empty.');
} else {
alert('myArray is empty.');
}
</script>
</body>
</html>
Output