All falsey values in JavaScript
Falsey values in JavaScript
false
- Zero of
Number
type:0
and also-0
,0.0
, and hex form0x0
(thanks RBT) - Zero of
BigInt
type:0n
and0x0n
(new in 2020, thanks GetMeARemoteJob) ""
,''
and``
- strings of length 0null
undefined
NaN
document.all
(in HTML browsers only)- This is a weird one.
document.all
is a falsey object, withtypeof
asundefined
. It was a Microsoft-proprietory function in IE before IE11, and was added to the HTML spec as a "willful violation of the JavaScript specification" so that sites written for IE wouldn't break on trying to access, for example,document.all.something
; it's falsy becauseif (document.all)
used to be a popular way to detect IE, before conditional comments. See Why is document.all falsy? for details
- This is a weird one.
"Falsey" simply means that JavaScript's internal ToBoolean
function returns false
. ToBoolean
underlies !value
, value ? ... : ...;
and if (value)
. Here's its official specification (2020 working draft) (the only changes since the very first ECMAscript specification in 1997 are the addition of ES6's Symbols, which are always truthy, and BigInt
, mentioned above:
Argument type Result Undefined Return false
.Null Return false
.Boolean Return argument. Number If argument is +0
,-0
, orNaN
, returnfalse
; otherwise returntrue
.String If argument is the empty String
(its length is zero), returnfalse
; otherwise returntrue
.BigInt If argument is 0n
, returnfalse
; otherwise returntrue
.Symbol Return true
.Object Return true
.
Falsey values in JavaScript
One dangerous issue of falsey values you have to be aware of is when checking the presence of a certain property.
Suppose you want to test for the availability of a new property; when this property can actually have a value of
0
or""
, you can't simply check for its availability usingif (!someObject.someProperty)
/* incorrectly assume that someProperty is unavailable */In this case, you must check for it being really present or not:
if (typeof someObject.someProperty == "undefined")
/* now it's really not available */Also be aware that
NaN
isn't equal to anything, even not to itself (NaN != NaN
).why all falsy values in javascript aren't equal to false when tested for equality
The
==
operator has its own semantics. You're comparing behaviors that are not defined to be the same.If you want to see how the normal "truthy/falsy" evaluation works, you should use
!value
or!!value
instead ofvalue == false
orvalue == true
:if (!null) console.log("hi");
if (!NaN) console.log("hi");Removing all falsy values from a javascript array, including NaN but excluding 0 and empty strings
NaN
is not equal to itself (i.e.NaN === NaN
evaluates to false), thus using it withindexOf
fails. Another approach that also conveys your goal ("filter() out all the falsy values except for '' and 0") better is the following:const values = ['', 0, 'one', NaN, 1, 'two', 2, null, 'three', undefined, 3, false];
const filteredValues = values.filter(value => value || value === '' || value === 0);
console.log(filteredValues);trouble with truthy/falsey
Edit:
The question was a bit confusing because of the snippet, I understood that you were trying to look for falsy values.
The reason why:
value => value == true
would print out false it's because none of the elements of the array is equal to
true
.You are correct about what a falsy value is, but that doesn't mean that a truthy value would be
==
totrue
.Here you can read more about it:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness
One way of checking for truthy values would be:
(values.some(value => value != false))
or
(values.some(value => !!value === true))
Old answer:
Because the method you use tests that at least one element in the array matches the condition.
You can read more here
If you want to check that all elements of the array matches the condition, then you can use
.every()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every
let values = [11, NaN, [], ""]
function checkForFalsey() {
if (values.every(value => value == false)) {
console.log("All values are falsey");
} else {
console.log("NOT all values are falsey");
}
}
checkForFalsey()check for falsy values in javascript
The forEach function doesn't detect if you delete elements, so when you modify the array, it will skip elements. The best way to do what you want is:
g.filter(e => e);
Understanding JavaScript Truthy and Falsy
From my understanding, I believe that var a = 1; is the only truthy and the rest are falsy’s - is this correct?
No.
var a = 0;
Number zero is falsy. However, note that the string zero
"0"
is truthy.var a = 10 == 5;
This is same as
var a = (10 == 5);
, so this is falsy.var a = 1;
var a = -1;
Any non-zero number including negative numbers is truthy.
Quoting from MDN
In JavaScript, a truthy value is a value that translates to true when evaluated in a Boolean context. All values are truthy unless they are defined as falsy (i.e., except for
false
,0
,""
,null
,undefined
, andNaN
).List of falsy values in JavaScript:From MDN
false
null
undefined
0
NaN
''
,""
,``
(Empty template string)document.all
0n
: BigInt-0
Check for falsy values on array
Try this code if you want to check for falsy values
Let me tell you that falsy values don't require to be boolean!
For Example, 0 is a falsy value however typeof(0) is number ..
The reason why your code returns an empty array is the if condition, you're checking if typeof(arr[i]) !== Boolean && arr[i]
this condition will always be false since typeof returns a string and Boolean is considered as an Object/ Constructor (which isn't a string)
function bouncer(arr) {
let word = []
for (let i = 0; i < arr.length; i++)
if (arr[i]) {
word.push(arr[i])
}
return word;
}
console.log(bouncer([false, null, 0, NaN, undefined, ""]));
Related Topics
Convert Form Data to JavaScript Object With Jquery
How to Obfuscate (Protect) JavaScript
Creating a Blob from a Base64 String in JavaScript
Detecting an Undefined Object Property
How to Replace Plain Urls With Links
How to Detect Page Zoom Level in All Modern Browsers
Is JavaScript Guaranteed to Be Single-Threaded
Remove Empty Elements from an Array in JavaScript
How to Enable Cors in Angularjs
Google Maps Js API V3 - Simple Multiple Marker Example
How to Pad a Value With Leading Zeros
What Does the Exclamation Mark Do Before the Function
Jquery: Return Data After Ajax Call Success