Unexpected result when checking undefined value - javascript

I have an array of objects with a length of at most 4 and at least 1. Here, I check which elements exist and do things accordingly.
function sendToGroup(receiver_group) {
if (receiver_group[0] !== undefined){
console.log(receiver_group[0])
}
if(receiver_group[1] !== undefined){
console.log(receiver_group[1])
}
if(receiver_group[2] !== undefined){
console.log(receiver_group[2])
}
if(receiver_group[3] !== undefined){
console.log(receiver_group[3])
}
}
When I give the array of 2 elements to this function, I see first and second element as expected in the console output but I also see an undefined in the line of
console.log(receiver_group[2])
How is this even possible? If it is undefined(which it is) this logging code should not get executed.
Edit: Chrome says the length of the array is 2. Which It is.
receiver_group is an array. which has the content of
[{id:12, name:"name", age:"21"}, {id:22, name:"name", age:25}]
Also same thing doesn't happen for the item 4 which has the index of 3.

It is also printing undefined, if I execute the below code:
if(1==2){}
In the console you can type a name of a variable (for example try
typing window) and it prints info about it. When you run any void
function (like console.log) from the console, it also prints out info
about the return value, undefined in this case.
So, the undefined printed after logging [0] and [1] value is the correct behavior as it is trying to print the return value which is undefined.
Please refer to the answer: Chrome/Firefox console.log always appends a line saying undefined

Related

Getting Uncaught TypeError: array_name[while_counter] is undefined

I am getting a perplexing error when running the following code:
while (typeof array1[while_counter] != undefined && while_counter <= while_counter_end) {
console.log (array1);
console.log (while_counter);
$('#element_'+array1[while_counter]['key1']).on('click', function( event ){
This leads to Uncaught TypeError: array1[while_counter] is undefined for the line with jQuery. At the same time, the console.log lines output an array and the while_counter numbers. console.log(array1[while_counter]); in the loop also outputs the expected output.
Also, this happens only on a live website I have at a webhost, while running it on a local site doesn't result in this error.
Does anyone know what could be causing this?
Just try debugging it with better logs
Print array1[while_counter] and array1[key1] in console log too.
is there any chance same code executing 2 time? First when array1 is without actual value
use correct comparison operator i.e. use !== instead of !=
while (typeof array1[while_counter] !== 'undefined' && while_counter <= while_counter_end) {

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

RowDataPacket value undefined

When I run my code it returns my value as undefined which is strange because if I run the entire array it shows all data.
Here is the code:
console.log(appid_cards[x].cards); (returns "undefined")
console.log(appid_cards[x].appid); (returns "undefined")
console.log(appid_cards[x]); (returns "appid=", "cards:")
for example this happens if I run a specific (existing row) :
console.log(appid_cards[x].cards); (returns "undefined")
console.log(appid_cards[x].appid); (returns "undefined")
console.log(appid_cards[x]); (returns "appid: 400250, cards: 8")
console.log(x); (returns "0")
so the X works for the entire RowDataPacket, but if I want to select a key then it somehow doesn't work.
I also check if maybe x would become greated then the number of rows but that is no the case because it is run in a "for" loop and it cannot be greater than appid_cards.length, I can call the entire array but once I start to specify the "cards" or "appid" it returns undefined.
Thanks for the help.
Found out that where I pushed the array something went wrong and fixed that piece of code, fixing this as well. Thanks for all the help !

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.

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