If statement throwing error for nonexistent object - javascript

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

Related

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);
}

How to Check the variable value is [""] in JavaScript

Example:
When I check a variable containing this value [""] it returns false.
var th=[]
th.push("");
if($("#multiselect").val()==th)
It returns always false.
Thank you.
Edit 1:
changed Var to var. It was a typo.
Edit 2:
Actually, the problem I faced was I was trying to get the value from a multi-select input. The multi-select input sometimes returns values as [""] even I haven't selected any values basically it's a plugin. So I was confused and I thought [""] is a fixed primitive value like 1, 10, "bla blah",.. So I tried to compare it with the same array as the right-hand side of the '=' operator.
It was stupid. Now I posted the solution to my problem and I explained my stupidity.
there are two things:
Change Var to var
You can use includes method of Array as:
var th = [] <==== chnage Var to var
th.push("");
if(th.includes($("#multiselect").val())) { <=== you can use includes method of array
// DO whatever you want
}
Make sure var is lowercased.
You are accessing th as an array, so you’ll need to specify the index of the value you are checking: th[0]
Use triple equals, too: .val()===th[0]
Double check the jquery docs if you’re still running into trouble.
Happy coding!
A couple of things to consider:
You have a typo in the code above; var is valid; Var is invalid.
Browser will aptly complain to solve this typo.
You are comparing an array to DOM value; this will always be false.
DOM is a costly process. Unless the value associated is dynamic, its better to read once, store value into a variable and continue processing instead of reading from DOM always.
You could choose to try something on these lines:
let arr = [1,2,3,4];
let domValue = $("#multiselect").val();
arr.push(5);
arr.map((el, ix) => {
if el === domValue return true; //or choose to do something else here.
});
var th=[]; //It is var not Var
th.push("");
if($("#multiselect").val()==th[0]) // change th to th[0]
I am unable to comment so having to use an answer for now. Are you trying to check if an array has any values? If so you can use
if(th.length){
// do something
}
If you want to check a normal variable for empty string you can simply use
if(th == “”){
//do something
}
I found the solution after a couple of days when I posted this question. Now I can feel how stupid this question was.
Anyway, I'm answering this question so it might help others.
Answer to my question:
When two non-primitive datatype objects(which is the Array here) are compared using an assignment operator, it compares its reference of the object. So the object creation of both arrays would be different. If I want to check the array has [""] value, I should do something like the below.
function isArrValEmptyCheck(value) {
return !value || !(value instanceof Array) || value.length == 0 || value.length == 1 && value[0] == '';
}
console.log(isArrValEmptyCheck([""]));//returns true
console.log(isArrValEmptyCheck(["value1"]));//returns false
Sorry for the late response. Thanks to everyone who tried to help me.

object with array type string causing a typeError

The best way to explain this is just to show you.
var condition = 70;
var formnames = new Array("wheelcheckbox1", "wheelcheckbox2","spokecheckbox","spokecheckbox2","tirecheckbox","tirecheckbox2","tirecheckbox3");
formnames.forEach(function(entry) {
console.log(obj.entry);
if(obj.entry == "") {
condition = condition - 10;
}
});
as you can see I used the console log to show how it needs to work
as that works perfect, however, using the array causes an error as
they're strings and not what the obj wants, it wants text without it being a string.
Any ideas?
for..in should not be used to iterate over an array. Consider using forEach instead.

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

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.

Undefined error in reading the property of object

Please help to solve the undefined error coming in my console while running the below code
Please see this JSbin also http://jsbin.com/ONOwujA/1/edit
data = [
{key:"home",value:"hk1"},
{key:"home",value:"hk2"},
{key:"home",value:"hk3"},
{key:"home",value:"hk4"},
{key:"product",value:"pk1"},
{key:"product",value:"pk2"},
{key:"product",value:"pk3"},
{key:"product",value:"pk4"},
{key:"service",value:"sk1"},
{key:"service",value:"sk2"},
{key:"service",value:"sk3"},
{key:"service",value:"sk4"}
];
myFilteredKey=[];
for(i=0;i<=data.length;i++){
if(myFilteredKey.indexOf(data[i].key)!=-1){
myFilteredKey.push(data[i].key);
console.log(data[i].key);
}
}
Use i < data.length. If the length is 3, the maximum index is 2.
Another problem with your code is that no element will be added to myFilteredKey. Since the array is already empty, no element will satisfy the condition myFilteredKey.indexOf(data[i].key)!=-1. Maybe you want to use === -1 instead, i.e. check whether the element is not in the array rather than whether it's in the array.

Categories

Resources