0

I have this jQuery code

if (date != !date) {
    console.log(date);
}

The date is an array, or null. If it's an array, I want to log it, if it is null I want to stop it right there. I thought the != !var was exactly for this purpose. Still when I try this, I do also get null console logs. How come?

CDspace
  • 2,639
  • 18
  • 30
  • 36
Asitis
  • 382
  • 3
  • 17

4 Answers4

2

x is always not equal to !x (this is what x!= !x means).

You want something like : does x exist ? Is it null ?

if (date != null) {
    console.log(date);
}

var x1;
var x2 = [1,2];

if(x1 != null) // <- false
   console.log(x1); 

if(x2 != null) // <- true
  console.log(x2);
Hearner
  • 2,711
  • 3
  • 17
  • 34
  • I wanted to catch all possible outcomes (null, undefined etc), but I guess `!= null` will do. – Asitis Dec 07 '16 at 15:56
  • 3
    @AlexTimmer `!= null` will be `true` for both `undefined` and `null`, but `!== null` will be `true` for `null` only. – Jed Fox Dec 07 '16 at 15:58
1

Try this, it should catch everything in the else...

if(Array.isArray(date)){
  console.log(date); 
}
else {
  console.log('not array');
}
curv
  • 3,796
  • 4
  • 33
  • 48
  • This is good, it fits perfectly as my var should always be an array and nothing else. – Asitis Dec 07 '16 at 15:59
  • 1
    Thanks @AlexTimmer - literally hundreds of ways you can do this - this just seemed to be the most verbose. To be honest you don't even need the else statement, depends on if you want to catch it or not. – curv Dec 07 '16 at 16:01
-1

Try this:

if (date){
    console.log(date);
}
-2

So you need to find out whether some value is an array or not. Here is another way to do this as recommended by the ECMAScript standard. For more infos about this see this post: Check if object is array?

var date = ['one', 'two', 'three'];
var txt = "bla ... bla ...";

if( Object.prototype.toString.call( date ) === '[object Array]' ) {
    console.log('is array');
} else {
    console.log(' not an array');
}

if( Object.prototype.toString.call( txt ) === '[object Array]' ) {
    console.log('is array');
} else {
    console.log('is not an array');
}
Community
  • 1
  • 1
Flyer53
  • 754
  • 6
  • 14