How to verify if array exist and its length in fewest steps? - javascript

I have some if statement, where I want to verify the length of an array. Let's say it is the following:
if (object.someArray.length > 1){
doSomething()
}
However, when someArray is not defined (maybe it is not defined for some object, which is possible), I get an error:
Cannot read property 'length' of null
Which makes sense, as object.someArray is not defined.
My question is: what is the best way to verify that the array exists AND its length, in fewest steps?
Thanks!

The very generic and full test : if array exist and is not empty
if(object && object.someArray && object.someArray.length)
For your case :
if(object.someArray && object.someArray.length > 1)
Edit : For those who don't know this is called duck-typing : we aren't checking really if the object is an array, we're considering that if that object has a property length, it is an array. Lot of library do that. As long as you don't store different types of javascript object (string/array/object) in the same variable, this code is safe.

Try to check array through Array.isArray
if (Array.isArray(object.someArray) && object.someArray.length > 1)

You can do it in one single condition like
if (object.someArray && object.someArray.length > 1){
//Do Something
}
if object.someArray is undefined, it will return false and the next condition will not be evaluated

the best way to verify that the array exists AND its length
The best way is to do exactly as you wrote:
if (array && array.length > 0 { ... }

You can check it this way.
if(object.someArray && object.someArray.length > 1) {
doSomething();
}
If the someArray does not exist then it will be false and it will never check for its length because of the short-circuit.

Related

Type of this is always object while checking for a valid Javascrip Object

I wrote a Prototype function in javascript to determine whether an entity is a valid Javascript object or not. Something like following
// Check if Object is Valid & Have at least one element
Object.prototype._isValidObject = function () {
return this && typeof this === 'object' && !Array.isArray(this) && Object.keys(this).length >= 1;
};
The problem is it is returning TRUE for most of the values, like even for string, cause this is treated like an object for any value, like arrays, strings or json etc. There may be other ways to do this, but I need to make a prototype function for this. Please determine the correct way to Determine whether a value is a valid Javascript object having atleast one item. Thanks
EDIT
By Valid Javascript / JSON Object I mean something like this:
{
id:100,
name:'somename',
email:'maiL#mail.com'
}
To be more precise following is what I want:
const j = {id:100,name:'somename', email:'maiL#mail.com'};
const s = "{id:100, name:'somename', email:'maiL#mail.com'}";
j._isValidObject(); // Should return true
s._isValidObject(); // Should return false
const j is valid for me cause it is an object having key-value pairs. const s is invalid for me cause it's a string representation of an object, not the object itself. const s can be converted to valid Object like const j, but right now const s is just a string.
EDIT
I have found a solution, and posted it in answers. Though I am not marking it as accepted answer since I'm not sure whether it's the best way to do it. If somebody has a better solution, please post it. Thanks
I have found a solution, though I am not marking as accepted answer since I'm not sure whether it's the best way to do it. If somebody has a better solution, please post it. Thanks
// Check if Object is Valid & Have at least one element
Object.prototype._isValidObject = function () {
return this
&& !(this instanceof String)
&& !Array.isArray(this)
&& Object.keys(this).length >= 1;
};

length and typeof == undefined being ignored, lodash

Hopefully, my codepen is clear enough, first time using it - https://codepen.io/jsfo011/pen/GRojmpw
notEmpty is JSON from my database. I wrote a function to loop through it and find the row that matches a parameter, returning the value.
If my function can't find a matching row, I want to return 0.
I figured what I had written would work, but I keep getting
"jQuery.Deferred exception: Cannot read property 'total_income' of undefined" "TypeError: Cannot read property 'total_income' of undefined
But it seems to work fine when it does match.
What am I missing?
If income after filtering does not have a single value (empty list), single[0] is undefined. So, the following code was trying to access a property "total_income" of undefined
income[0]["total_income"]
You need to make sure that the property is accessed only if the parent object income[0] is valid.
One way to do this is by adding another check to make sure that income has at least a single value in the list before we access it like so:
if (income && income.length) {
if (income[0]["total_income"] !== undefined) {
return parseFloat(income[0]["total_income"]);
}
}
The line checks to make sure that income is defined and has at least one value.
Output:
Empty Data - 0
Found - 1000
Not found - 0
Hope this helps in understanding the issue.
why not just using lodash.get( ) with default value 0:
function calculate(data, income_type) {
let income = _.filter(data, {'income_type': income_type});
let incomeValue = _.get(income, '0.total_income', 0);
return parseFloat(incomeValue);
}

Check of object length in Javascript

I want to check if my object is null or the length is 0. I have tried something like this without any luck.
if (this.get('goodie.pincodes.firstObject') == null || this.get('goodie.pincodes.firstObject.pin').length == 0) {
I solved this in a different way. Making sure that entries with no length allways returns null. Then only asking if the object is null.
this.get('goodie.pincodes.firstObject') == null

javascript undefined not null, not empty issue

Is the statement:
if(attachmentId!=null && attachmentId.length>0&& attachmentId !='undefined'){
//do something
}
equivalent to:
if (attchmentId) {
//do something
}
thanks for the help
Writing :
if (attchmentId)
is the equivalent of:
if(
attchmentId != undefined &&//NO QUOTE
attchmentId != '' &&
attchmentId != null &&
attchmentId != false &&
attchmentId != 0
)
They're not equivalent but the third test attachmentId !='undefined' was probably an error (did you want attachmentId !=undefined ?).
Another example of difference is that 0 doesn't pass the first test but pass the second one.
You must decide what's important to you before you try to write the test. If you know you start with a string and you want to test if it's defined and not empty, then you may use the second test.
It can be reduced to this:
if (attachmentId && attachmentId.length > 0) {
//do something
}
This will do for arrays and more complex objects that happen to have a length property. If attachmentId is supposed to be a string the code above will work the same, but the second part will basically be a noop, so you can just go with:
if (attachmentId) {
//do something
}
I am assuming the comparison against 'undefined' was a mistake - do that and you're not checking if something is actually undefined. You're checking it it is different from a literal string that says "undefined".
Also you check the variable first due to the short circuit rule. It it's either null or not defined you don't care about the rest. Otherwise, if you tried evaluating the length before checking if it's undefined or null you could throw an error there.

If statement throwing error for nonexistent object

The answer to this question seems like it would be obvious, but I'm always looking to improve my semantics, so bear with me.
I have an array structure with individual items containing X,Y coordinates
var example = new Array();
example.push({x:0,y:0});
In my code I have a set interval that updates my canvas and checks for certain conditions. Including one similar to this
if(example[0].x == other.x && example[0].y == other.y)
{
//do something
}
The issue is that the array is very dynamic, and when the code is first executed the example array is empty. Hence, Chrome throws errors along the lines of "Cannot get property x". To shut up the console, I added a dummy item to the array {x:"~", y:"~"} but it seems really unintuitive. Have I implemented an undesirable data structure? What's a simple way to handle if statements for objects that... don't exist?
Why don't you just check whether the array has elements?
if (example.length && ...)
Or whether the first element is true:
if (example[0] && ...)
if (0 in example
&& example[0].x == other.x && example[0].y == other.y) {
// do something
}
(This works for arbitrary index, not just 0; if you just want to check if the array is non-empty, example.length as shown by melpomene is good.)
You should be able to check on the first-level element (i.e. 'example') - JavaScript usually throws errors like this when you try to access a property of an element that is null or undefined. Like some others have already shown:
if(example[0] && example[0].x === other.x)
The point is though that JavaScript will let you have example[0] and return as you like, but once you try to access that property, you're out of luck:
var example = [];
//undefined
example
//[]
example[0]
//undefined <--- this is a falsy value, will evaluate false in a check
example[0].x
//TypeError: Cannot read property 'x' of undefined

Categories

Resources