October 22, 2024
Chicago 12, Melborne City, USA
javascript

Why does javascript output the same, even when I negate the condition?


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



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video