1

I have an array variable like Array[0], and now I need to check whether that Array[0] contains value or not inside of it. What should I do?

2
  • Possible duplicate of stackoverflow.com/q/610842/544184 Commented Jan 11, 2012 at 11:55
  • And what's your definition of whether or not the variable "contains value"? Commented Jan 11, 2012 at 12:00

4 Answers 4

3

If you have an array and call it eg. list, then you can check if it has some elements in the following manner:

if (list.length){
    // has some elements (exactly list.length elements)
} else {
    // does not have any elements
}

See the following for details: Documentation on length property of Array objects in JavaScript

Sign up to request clarification or add additional context in comments.

Comments

1
if(array[0] !== undefined){
 // array[0] is defined.
}

Comments

1
//pass array variable to this function

function isEmpty(array){
   if(array.length == 0)
    return true;
   else
    return false; 
}

3 Comments

Why would you want the added complexity and overhead using a function for this?
if anyone dont want to use functions he can just check "array.length == 0" but if number of times wants to check it is empty or not that time, instead of repeating code i think function is good option...
Question asks to check if first index is empty, not if the array is empty.
1

Checks if that array exists and does something if not so.

if(!array[0])
{
  //do something
}

6 Comments

However you need it, but thanks for the correction :) I'm always open to good tips.
@Karlisson: You say false, 0 etc. are not "values"? OP asked: "I need to check whether that Array[0] contains value or not inside of it".
@Karlisson: The original was "need to check weather that array[0] containing value or not inside of if...", so I would not expect it to stay unedited ;) But it is matter of interpretation in that case, I suppose ;)
The code would generally work but if(foo[0] !== undefined){} is more accurate, as your code would fail if it had a false value.
@manticore: It depends. undefined sometimes can be overwritten with something else (although can be restored by simple trick). You can also use typeof foo[0] !== 'undefined', I believe. Please search on StackOverflow for other tipses on how to deal with undefined being actually defined (such as when you invoke (function(undefined){/* your code here */}());, the undefined variable within the anonymous function is actually undefined, as you do not pass it within call / brackets calling the function).
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.