0

I've been wondering about this syntax I picked up when attempting to accomplish some functionality using jQuery/javascript and was wondering if this is actually valid syntax or not. It seems to work, but it could be that javascript is just defaulting for true in the if-clause. I assumed it just validates whether or not the array has entries/is a valid array. Can anyone explain to me if the following is valid/invalid and if it is valid, what is it checking exactly?

var arrVariable = new Array();

... push things to array, etc.

if(arrVariable)    {
     ... doing stuff with array.    
}
4
  • Objects are always truthy. Commented Jul 23, 2015 at 17:48
  • 1
    Exactly what do you mean by valid array? If you are looking for elements in the array I would use arrVariable.length. Commented Jul 23, 2015 at 17:48
  • arrays are objects too :) and empty arrays... Commented Jul 23, 2015 at 17:49
  • try yo use Array.isArray(arrVar) && arrVar.length Commented Jul 23, 2015 at 17:51

2 Answers 2

3
if(arrVariable) {

}

This if statement evaluates if arrVariable is truthy or falsy.

The following values are always falsy:

  • false
  • 0
  • ""
  • null
  • undefined
  • NaN

All other values are truthy (source).

I assumed it just validates whether or not the array has entries/is a valid array.

This is not true. An empty array is an object and is therefore truthy. You can test this quite easily:

var arr = [];
if (arr) {
    console.log('arr is empty, but truthy, so this statement executes');
}
Sign up to request clarification or add additional context in comments.

2 Comments

Also note that "false" is truthy, while false is not.
Oh wow, I never knew there was such a thing as "truthy" or "falsy" in javascript. Thanks for the answer and explanation!
0
var arr = ["one", "two"];

Check if the array has entries in it:

if (arr.length) {
    //There is at least one entry in the array
}

To check if it's an array:

if (arr instanceof Array) {
    //It's an array
}

Comments

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.