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 -
1) How to check if array is empty or null or undefined using javascript (Basic Cheking)
<!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
2) How to check if array is empty using javascript
<!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
3) How to check if array is null using javascript
<!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
4) How to check if array is undefined using javascript
<!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