Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How [ ] is converted to Boolean in JavaScript?
In JavaScript, an empty array [] is considered a truthy value when converted to Boolean. This might seem counterintuitive, but it follows JavaScript's type coercion rules for objects.
Converting [] to Boolean
Use the Boolean() method to explicitly convert an empty array to Boolean:
<!DOCTYPE html>
<html>
<body>
<p>Convert [] to Boolean</p>
<script>
var myVal = [];
document.write("Boolean: " + Boolean(myVal));
</script>
</body>
</html>
Boolean: true
Why [] is Truthy
In JavaScript, all objects (including arrays) are truthy values, regardless of their content:
<!DOCTYPE html>
<html>
<body>
<script>
console.log(Boolean([])); // true - empty array
console.log(Boolean([1, 2, 3])); // true - filled array
console.log(Boolean({})); // true - empty object
console.log(Boolean(null)); // false - null is falsy
console.log(Boolean(undefined)); // false - undefined is falsy
</script>
</body>
</html>
true true true false false
Falsy vs Truthy Values
JavaScript has only 6 falsy values. Everything else, including empty arrays, is truthy:
| Value | Boolean Result | Type |
|---|---|---|
false |
false | Falsy |
0 |
false | Falsy |
"" |
false | Falsy |
null |
false | Falsy |
undefined |
false | Falsy |
NaN |
false | Falsy |
[] |
true | Truthy |
Practical Example
This behavior affects conditional statements:
<!DOCTYPE html>
<html>
<body>
<script>
var arr = [];
if (arr) {
console.log("Empty array is truthy!");
}
// To check if array is actually empty:
if (arr.length === 0) {
console.log("Array has no elements");
}
</script>
</body>
</html>
Empty array is truthy! Array has no elements
Conclusion
An empty array [] converts to true in JavaScript because arrays are objects, and all objects are truthy. Use arr.length === 0 to check if an array is actually empty.
Advertisements
