I am a student, and I am doing a project for school.
While I was working on it, I encountered a problem and discovered something weird.
I needed to check if a something is null or a empty string, but for some reason it didn’t work.
Here’s the code snippet:
if(!data.data == null && !data.data == 'null' && !data.data == ''){ // Some code here... }
It didn’t work, so I tried this:
console.log(!data.data == null)
console.log(!data.data == 'null')
console.log(!data.data == '')
and when the data.data wasn’t empty, the output was this:Console output: false false true
So i change it to:
console.log(data.data == null)
console.log(data.data == 'null')
console.log(data.data == '')
(the data.data value is the same)
the output changed to this:Console output: false false false
So I tried to test this in consoleJavascript console
Here’s it copied:
var data = 'aaa'
console.log(data)
aaa
console.log(data == null)
false
console.log(!data == null)
false
console.log(!data == '')
true
console.log(data == '')
false
console.log(!data === null)
false
console.log(data === null)
false
data = null
null
console.log(data === null)
true
console.log(!data === null)
So the question is, When the value is not null, why does it always output false, even when I negate it, but when the value is null, negating it works?
PS: I am sorry if this is a stupid question, or not too clear, but I am not that good, and really confused right now
2
Answers
You need to understand how data behaves when it has a value, such as
data = 'aaa'
. In this case, data will hold the value'aaa'
. However, if you check!data
, it will evaluate whether data has a value; if there is no value,!data
will returnfalse
.When you use the comparison operator
==
with false, all values like0, "0", ""
will be coerced into false. Therefore, when comparing0 == false
or"" == false
, the result will be true.When you use the strict equality operator
===
, it not only compares the values but also checks the data types.The fundamental issue here is where you are putting the exclamation marks in your code.
When you write
!data == null
, javascript does two things:!data
– which will return false if data is truthy (generally speaking – if it has a value that is not false or zero). It applies the logical NOT operator!data
will be a boolean – eithertrue
orfalse
– but NEVERnull
.It will do the first action (negating the value) first per JavaScript’s operation precedence. You could reverse that precedence by writing
!(data == null)
, which ill give a result more similar to what you are trying to do.What you probably meant to do was
data != null
– which will check wether data is not equal null. This is called the inequality operator.