-1

I just started programming with javascript no long ago. But I am still confused with the way it handles arrays. the problem is that I have an array in which there some content as undefined. I want to check for those undefined values and escape them. How do I do it. the following code is not working and I have not found a way to solve this problem.

if(myarray[0]!=='undefined')

if(myarray[0])!='undefined') // I have also tried


if(myarray[0]).search('undefined')==(-1)) // and also this

however none of these options is working. I could see when debugging that the value in the array is 'undefined' but the condition is never met. once again my aim is to do something when it is not undefined. please how could I do it. I found a similar question Test if something is not undefined in JavaScript but it does not work

Community
  • 1
  • 1
zeroday
  • 153
  • 2
  • 14
  • possible duplicate of [Test if something is not undefined in JavaScript](http://stackoverflow.com/questions/7041123/test-if-something-is-not-undefined-in-javascript) – JJJ Dec 05 '14 at 19:39

4 Answers4

1

You are comparing undefined to 'undefined', which is a string so its different. You need to compare like this:

myarray=[undefined];
if(myarray[0]!==undefined){
    console.log(4)
}
juvian
  • 15,875
  • 2
  • 37
  • 38
  • This is unsafe because undefined is a writeable global property. –  Dec 05 '14 at 19:40
  • well, highest voted answer from http://stackoverflow.com/questions/7041123/test-if-something-is-not-undefined-in-javascript does the same. Still, good to know – juvian Dec 05 '14 at 19:43
  • [Not since JavaScript 1.8.5](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined), for those interested. – chazsolo Dec 05 '14 at 19:55
1

You're comparing the myarray[0] value to a string value of undefined.

What you need is this:

if (typeof(myarray[0]) !== 'undefined')

Hope this helps!

huysentruitw
  • 27,376
  • 9
  • 90
  • 133
1

juvian provided a good answer. You need to use undefined instead of 'undefined' because you are comparing your array to a string.

On my current project, I use underscore to check for undefined. It's pretty simple and straight-forward.

var array = [];
if (_.isUndefined(array));

http://underscorejs.org/#isUndefined

Sam Neely
  • 123
  • 1
  • 6
0

You should check it as follows: if(typeof(myarray[0]) != 'undefined')

Suthan Bala
  • 3,209
  • 5
  • 34
  • 59