Will this work for testing whether a value at position index
exists or not, or is there a better way:
if(arrayName[index]==""){
// do stuff
}
Will this work for testing whether a value at position index
exists or not, or is there a better way:
if(arrayName[index]==""){
// do stuff
}
Conceptually, arrays in JavaScript contain array.length
elements, starting with array[0]
up until array[array.length - 1]
. An array element with index i
is defined to be part of the array if i
is between 0
and array.length - 1
inclusive. If i is not in this range it's not in the array.
So by concept, arrays are linear, starting with zero and going to a maximum, without any mechanism for having "gaps" inside that range where no entries exist. To find out if a value exists at a given position index (where index is 0 or a positive integer), you literally just use
if (i >= 0 && i < array.length) {
// it is in array
}
Now, under the hood, JavaScript engines almost certainly won't allocate array space linearly and contiguously like this, as it wouldn't make much sense in a dynamic language and it would be inefficient for certain code. They're probably hash tables or some hybrid mixture of strategies, and undefined ranges of the array probably aren't allocated their own memory. Nonetheless, JavaScript the language wants to present arrays of array.length
n as having n members and they are named 0 to n - 1, and anything in this range is part of the array.
What you probably want, however, is to know if a value in an array is actually something defined - that is, it's not undefined
. Maybe you even want to know if it's defined and not null
. It's possible to add members to an array without ever setting their value: for example, if you add array values by increasing the array.length
property, any new values will be undefined
.
To determine if a given value is something meaningful, or has been defined. That is, not undefined
, or null
:
if (typeof array[index] !== 'undefined') {
or
if (typeof array[index] !== 'undefined' && array[index] !== null) {
Interestingly, because of JavaScript's comparison rules, my last example can be optimised down to this:
if (array[index] != null) {
// The == and != operators consider null equal to only null or undefined
}
Short and universal approach
If you want to check any array if it has falsy values (like false, undefined, null or empty strings) you can just use every() method like this:
array.every(function(element) {return !!element;}); // returns true or false
For example:
['23', null, 2, {key: 'value'}].every(function(element) {return !!element;}); // returns false
['23', '', 2, {key: 'value'}].every(function(element) {return !!element;}); // returns false
['23', true, 2, {key: 'value'}].every(function(element) {return !!element;}); // returns true
If you need to get a first index of falsy value, you can do it like this:
let falsyIndex;
if(!['23', true, 2, null, {key: 'value'}].every(function(element, index) {falsyIndex = index; return !!element;})) {
console.log(falsyIndex);
} // logs 3
If you just need to check a falsy value of an array for a given index you can just do it like this:
if (!!array[index]) {
// array[index] is a correct value
}
else {
// array[index] is a falsy value
}
if(typeof arr ==='object' && arr instanceof Array ){
if(!arr.length){
println 'empty'
}else{
printn 'not Empty'
}
}else{
println 'Null'
}
If you mean by 'Null' -> Its elements are null or equals to '' , in this case : Check if the array is empty after filtering all 'null' elements
if(!arr.clean().length){return 'is null'}
Of course ,Add Clean method before :
Array.prototype.clean=function(){return this.filter(function(e){return (typeof e !=='undefined')&&(e!= null)&&(e!='')})}
It depends on what you mean with "empty".
When you attempt to get the value of a property on an object which has no property with that name, you will get the value undefined
.
That's what happens with sparse arrays: not all indices between 0
and array.length-1
exist.
So you could check if array[index] === undefined
.
However, the property index
could exist with an undefined
value. If you want to filter out this case, you can use the in
operator or hasOwnProperty
, as described in How do I check if an object has a property in JavaScript?
index in array;
array.hasOwnProperty(index);
If you want consider an existing property with an undefined
or null
value to not exist, you can use the loose comparison array[index] == undefined
or array[index] == null
.
If you know the array is not sparse, you could compare index
with array.length
. But to be safe, you may want to ensure that index
really is an array index, see Check if property name is array index
I would recommend creating a function like this:
function isEmptyEl(array, i) {
return !(array[i]);
}
You could call it like this:
if (isEmptyEl(arrayName, indexVal)) {
console.log('arrayName[' + indexVal + '] is empty');
}
Forcing the developer to adhere to the isEmptyEl interface will catch input errors such as an undefined arrayName or indexVal variables.
(It's generally good practice to program defensively when programming in Javascript.)
You would get an error thrown like this if arrayName was not defined:
Uncaught ReferenceError: arrayName is not defined
at <anonymous>:2:15
at Object.InjectedScript._evaluateOn (<anonymous>:895:140)
at Object.InjectedScript._evaluateAndWrap (<anonymous>:828:34)
at Object.InjectedScript.evaluate (<anonymous>:694:21)
Similar results for an undefined indexVal.
You get an error if the array or index values do not exist.
For valid input, you'll only get a true if arrayName[indexVal] is any of the following:
I would like to point out something a few seem to have missed: namely it is possible to have an "empty" array position in the middle of your array. Consider the following:
let arr = [0, 1, 2, 3, 4, 5]
delete arr[3]
console.log(arr) // [0, 1, 2, empty, 4, 5]
console.log(arr[3]) // undefined
The natural way to check would then be to see whether the array member is undefined, I am unsure if other ways exists
if (arr[index] === undefined) {
// member does not exist
}
OK, let's first see what would happens if an array value not exist in JavaScript, so if we have an array like below:
const arr = [1, 2, 3, 4, 5];
and now we check if 6 is there at index 5 or not:
arr[5];
and we get
undefined
...
So that's basically give us the answer, the best way to check if undefined, so something like this:
if("undefined" === typeof arrayName[index]) {
//array value is not there...
}
It's better NOT doing this in this case:
if(!arrayName[index]) {
//Don't check like this..
}
Because imagine we have this array:
const arr = [0, 1, 2];
and we do:
if(!arr[0]) {
//This get passed, because in JavaScript 0 is falsy
}
So as you see, even 0 is there, it doesn't get recognised, there are few other things which can do the same and make you application buggy, so be careful, I list them all down:
undefined
''
in
operatorThis question age is about 10 years and it is surprising that nobody mention about this yet - however some people see the problem when we use delete
operator (e.g here). This is also a little bit counter intuitive solution but the in
operator which works in 'object world' can also work with arrays (because we can look on array indexes like on 'keys'...). In this way we can detect and distinct between undefined
array value and value (index) removed by delete
if(index in arrayName) {
// do stuff
}
let arr = [0, 1, 2, 3, null, undefined,6]
delete arr[2]; // we delete element at index=2
if(2 in arr) console.log('You will not see this because idx 2 was deleted');
if(5 in arr) console.log('This is element arr[5]:', arr[5]);
// Whole array and indexes bigger than arr.length:
for(let i=0; i<=9; i++) {
let val = (i in arr) ? arr[i] : 'empty'
let bound = i<arr.length ? '' : '(out of range)'
console.log(`${i} value: `, val, bound);
}
console.log('Look on below aray on chrome console (not in SO snippet console)');
console.log('typeof arr:', typeof arr);
console.log(arr);
Chrome console reveals some info about snippet array with deleted index 2 - this index actually not exists at all (!!!) (same way as key is removed from object). What is also interesting here array is viewd as key-value pairs (we even see 'length' key). It is also interesting that typeof arr
is Object (!!!), the delete
and in
operator works like for JS objects
(also square brackets notation arr[idx]
and obj[key]
is similar) - so it looks like array is some special JS object in the core.
To get similar effect without delete
define array as follows
[0, 1,, 3, null, undefined, 6] // pay attention to double comma: ",,"
With Lodash, you can do:
if(_.has(req,'documents')){
if (req.documents.length)
_.forEach(req.documents, function(document){
records.push(document);
});
} else {
}
if(_.has(req,'documents'))
is to check whether our request object has a property named documents
and if it has that prop, the next if (req.documents.length)
is to validate if it is not an empty array, so the other stuffs like forEach
can be proceeded.
To check if it has never been defined or if it was deleted:
if(typeof arrayName[index]==="undefined"){
//the index is not in the array
}
also works with associative arrays and arrays where you deleted some index
To check if it was never been defined, was deleted OR is a null or logical empty value (NaN, empty string, false):
if(typeof arrayName[index]==="undefined"||arrayName[index]){
//the index is not defined or the value an empty value
}
I ran into this issue using laravel datatables. I was storing a JSON value called properties
in an activity log and wanted to show a button based on this value being empty or not.
Well, datatables was interpreting this as an array if it was empty, and an object if it was not, therefore, the following solution worked for me:
render: function (data, type, full) {
if (full.properties.length !== 0) {
// do stuff
}
}
An object does not have a length property.
I think this decision is appropriate for guys who prefer the declarative functional programming over the imperative OOP or the procedural. If your question is "Is there some values inside? (a truthy or a falsy value)" you can use .some
method to validate the values inside.
[].some(el => el || !el);
function isEmpty(arr) { ... }
.[].length
resulting to 0
which is dangerous in some cases.[].length > 0
saying "Is its length greater than zero?"Advanced examples:
[ ].some(el => el || !el); // false
[null].some(el => el || !el); // true
[1, 3].some(el => el || !el); // true
when you create empty array values ARE NOT undefined, they are EMPTY
var arr = new Array(10); // (10) [empty × 10]
but when you get item by index receive undefined
arr[0]; // undefined
so you can't know by === comparing if they are undefined or empty
we can make it by using JSON.stringify, converting whole array it replaces empty values with null
JSON.stringify(arr); // "[null,null,null,null,null,null,null,null,null,null]"
JSON.stringify(arr[0]); // but for single item it returns undefined
so real check for empty value:
arr[0] !== null && JSON.stringify(arr.map(item => !item)).slice(1, -1).split(',')[0] === 'null'
false
instead existing values (ensure stringified structure to be comma-separated without redundant commas)null
You can use Loadsh library to do this more efficiently, like:
if you have an array named "pets", for example:
var pets = ['dog', undefined, 'cat', null];
console.log(_.isEmpty(pets[1])); // true
console.log(_.isEmpty(pets[3])); // true
console.log(_.isEmpty(pets[4])); // false
_.map( pets, (pet, index) => { console.log(index + ': ' + _.isEmpty(pet) ) });
To check all array values for null or undefined values:
var pets = ['dog', undefined, 'cat', null];
console.log(_.isEmpty(pets[1])); // true
console.log(_.isEmpty(pets[3])); // true
console.log(_.isEmpty(pets[4])); // false
_.map( pets, (pet, index) => { console.log(index + ': ' + _.isEmpty(pet) ) });
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
Check more examples in http://underscorejs.org/