Cannot read property '0' of undefined - javascript error? - javascript

I have a drop down menu, and when I select the 'All' option, it gives me this error on the console:
TypeError: Cannot read property '0' of undefined
at n.$scope.onSearchByChanged (http://localhost:8080/js/jenkinsVersion/directives/assignment-filter.js:70:81)
So, I went to my script, function, line 70,character 81 :
$scope.onSearchByChanged = function () {
if ($scope.filter.list.searchBy == 'DEPARTMENT_CODE' && !$scope.filterScope.departments) {
$scope.loadDepartments();
} else if ($scope.filter.list.searchBy != 'DEPARTMENT_CODE') {
$scope.filter.list.departmentId = 0;
}
if ($scope.filter.list.searchBy == 'GROUP' && !$scope.filterScope.editorGroups) {
$scope.loadEditorGroups();
} else if ($scope.filter.list.searchBy != 'GROUP') {
$scope.filter.list.groupId = $scope.filterScope.editorGroups[0].id; //line 70
}
$scope.clearFilter('text');
};
if ($scope.filter.list.searchBy == 'GROUP' && !$scope.filterScope.editorGroups) {
$scope.loadEditorGroups();
}
if ($scope.filter.list.searchBy == 'DEPARTMENT_CODE' && !$scope.filterScope.departments) {
$scope.loadDepartments();
}
$scope.isStatusSelected = function (status) {
return _.indexOf($scope.filter.list.talentAssignmentStatuses, status) > -1;
};
$scope.selectTalentAssignmentStatus = function (status) {
$scope.clearFilter('text');
if ($scope.isStatusSelected(status)) {
_.remove($scope.filter.list.talentAssignmentStatuses, function (el) {
return status == el;
});
} else {
$scope.filter.list.talentAssignmentStatuses.push(status);
}
};
here is the loadEditorGroups function :
$scope.loadEditorGroups = function () {
Reference.getEditorGroups($scope, function (response) {
$scope.filterScope.editorGroups = response.list;
if ($scope.filterScope.editorGroups.length > 0) {
$scope.filter.list.groupId = $scope.filterScope.editorGroups[0].id
}
});
};
I'm still learning JS. Why is this error being thrown? When I change the value of the item I want to retrieve from that editorGroups list it just gives me the same error but with the corresponding number. Your help would be appreciated, please let me know if I can supply further information. Thank you!

Your logic for this if-else block is probably wrong:
if ($scope.filter.list.searchBy == 'GROUP' && !$scope.filterScope.editorGroups) {
$scope.loadEditorGroups();
} else if ($scope.filter.list.searchBy != 'GROUP') {
$scope.filter.list.groupId = $scope.filterScope.editorGroups[0].id; //line 70
}
The program will enter the else if block when both:
the if condition is false, that is: ($scope.filter.list.searchBy == 'GROUP' && !$scope.filterScope.editorGroups) == false
the else if condition is true, that is: ($scope.filter.list.searchBy != 'GROUP') == true
We can take these two statements and simplify them:
!($scope.filter.list.searchBy == 'GROUP' && !$scope.filterScope.editorGroups) && ($scope.filter.list.searchBy != 'GROUP')
($scope.filter.list.searchBy != 'GROUP' || $scope.filterScope.editorGroups) && ($scope.filter.list.searchBy != 'GROUP')
($scope.filter.list.searchBy != 'GROUP')
In step 2, I applied De Morgan's law to simplify !(A && B) to (!A || !B).
In step 3, I simplified the &&, since (A || B) && A is the same as just A.
So really, all we know when we enter the else if block is that searchBy != 'GROUP'. We do not know anything about editorGroups, and indeed, it may be undefined!
What you're probably looking for is:
if ($scope.filter.list.searchBy == 'GROUP' || !$scope.filterScope.editorGroups) {
$scope.loadEditorGroups();
} else if ($scope.filter.list.searchBy != 'GROUP') {
$scope.filter.list.groupId = $scope.filterScope.editorGroups[0].id;
}
Notice the || in the if condition. This ensures that the else if is executed only when ($scope.filter.list.searchBy != 'GROUP' && $scope.filterScope.editorGroups), so that editorGroups[0] will not give an error. I don't know enough if this is what you intended this code to do, so correct me when I'm wrong. :-)

70:81 means line 70, character 81.
The problem is at editorGroups[0]: If editorGroups is undefined, it cannot read editorGroups[0] because undefined has no property called 0.
Make sure that editorGroups isn't undefined and you'll be fine!

Related

Firebase Data validation not matching with data

I have a click button which is validating data from firebase firestore, but it is not giving the correct output as in the checks applied are getting failed.
createAptBtn.onclick = () => {
if (category.value === "" || email.value === "" || day.value === "" || time.value === "") {
promptContent.innerText = "All fields are required."
}
else if (category.value === "New") {
db.collection("recordsDb").onSnapshot((querySnapshot) => {
querySnapshot.forEach((doc) => {
//Condtion 1
if (email.value === doc.data().email && day.value === doc.data().day && time.value === doc.data().time) {
promptContent.innerText = "Email already exists."
}
//Condition 2
if (email.value !== doc.data().email && day.value === doc.data().day && time.value === doc.data().aptTimeSlot) {
promptContent.innerText = "Slot already filled."
}
//Condition 3
if (email.value === doc.data().email || mobile.value === doc.data().mobile) {
promptContent.innerText = "User already exits."
}
// Condition 4
if(email.value !== doc.data().email && day.value !== doc.data().day && time.value !== doc.data().time) {
promptContent.innerText = "Account created."
}
})
})
}
}
Also even when one of the condition is true it still outputs the else statement which should work when all ifs are getting failed.
However, condition 4 is an else statement but since its not working I'm using it as an if statement by adding some checks in it which though fails.
How do I fix this?

How do I check nested If statements in JavaScipt

I'm new to JavaScript, so I'm currently working on a script that is supposed to update a string called Wasl_Status. These are the for conditions I'm trying to check:
Here is my code so far:
if (analog2 == 0) {
return "Tamper Weight";
}
if ((analog1 == 0) && (speed == 0)) {
return "Parked Device Disconnected";
}
if ((analog1 == 0) && (speed > 0)) {
return "Moving Device Disconnected";
if ((ignition == true) && (speed == 0))
return 'Parked Engine On';
if ((ignition == false) && (speed == 0))
return 'Parked Engine Off';
if (speed > 0)
return "Moving";
}
When I test it, the Wasl_Status only outputs the first three conditions and it ignores all the last three conditions. How do I make it to check every condition and return all 6 values? What I read so far is to create an array but current instructions say I must do nested if statements. I hope my question is clear. Thank you.
While it's correct, what you're doing, I think it's easier to read and follow the code if you, in most cases, try to return the value at the end of the function:
var message = 'no statements fit';
if (analog2 == 0) { message = "Tamper Weight"; }
else if (analog1 == 0 && speed == 0) { message = "Parked Device Disconnected"; }
else if (analog1 == 0 && speed > 0) {
message = "Moving Device Disconnected";
if (ignition == true && speed == 0) { message = 'Parked Engine On'; }
else if (ignition == false && speed == 0) { message = 'Parked Engine Off'; }
else if (speed > 0) { message = "Moving"; }
}
return message;
Then you would see, in an easier way, what is returning and when:
if ((analog1 == 0) && (speed > 0)) {
return "Moving Device Disconnected";
// ... everything after this code will never be executed because the function "stops" executing after a return.

Javascript Syntax - if statement

i have the following object:
var quarters = {
q1:false,
q2:false,
q3:false,
q4:{name: "i'm q4"}
}
My question is why the following IF is returning true?
if (quarters.q1 == quarters.q2 == quarters.q3 == quarters.q4 == false)
How can i ask if all quarters are false?
The reason I'm not using !quarters.q1 && !quarters.q2 && !quarters.q3 && !quarters.q4 is because sometimes, some of the properties are not defined at all.
why the following IF is returning true?
Assuming toppingOrder is quarters, lets fill it in and see what we have
if (toppingOrder.q1 == toppingOrder.q2 == toppingOrder.q3 == toppingOrder.q4 == false)
// same as
if (false == false == false == {name: "i'm q4"} == false)
// same as
if ((((false == false) == false) == {name: "i'm q4"}) == false)
// same as
if (((true == false) == {name: "i'm q4"}) == false)
// same as
if ((false == {name: "i'm q4"}) == false)
// same as
if (false == false)
// same as
if (true)
How can i ask if all quarters are false?
You either have to loop, use a logical AND && or some Array method like .every
// logical AND `&&`
if (
false === toppingOrder.q1
&& false === toppingOrder.q2
&& false === toppingOrder.q3
&& false === toppingOrder.q4
) // ...
// Array `.every`
if (
[toppingOrder.q1, toppingOrder.q2, toppingOrder.q3, toppingOrder.q4].every(
function (e) {return e === false;}
)
) // ...
It is actually much easier to test all true, so consider if you can phrase your if like that instead, e.g. using logical NOT !
if (!toppingOrder.q1 && !toppingOrder.q2 && !toppingOrder.q3 && !toppingOrder.q4) // ...
// or
if (
[!toppingOrder.q1, !toppingOrder.q2, !toppingOrder.q3, !toppingOrder.q4].every(Boolean)
) // ...
quarters.q1 == quarters.q2 == quarters.q3 == quarters.q4 == false
true == quarters.q3 == quarters.q4 == false
false == quarters.q4 == false
true == false
What you are essentially doing is this
everything will execute from left to right, unless you set the order (with ( ))
you could go this way about it
function get_bool(quarters){
for(k in quarters)
{
if(quarters[k] != false)
{
return true;
}
}
return false;
}

OR and AND conditions not returning as expected - What is best way to implement it?

I have an If statement that using || with an && operator e.g if((a || b) && c) however it is only works with the first condition i.e a but not with second i.e b even though running the debugger I can see that the condition is met and it goes to the correct line of code. Is there a better way to get this to work on both conditions?
code I have now:
function _getCatFormGUID(catName) {
debugger;
var dept = Browser.getValue(getElement("126D81CA203C21CF014C8A3550227892FE4B4A6A"));
if((catName == '1' && dept == "Entwicklung") || (catName == '7' && dept == "Entwicklung")){
return "A270AE7F957A74EF0842403EEA0032017567F3E8";
}
if((catName == '1' && dept != "Entwicklung") || (catName == '7' && dept != "Entwicklung")) {
return "8EDD0768A7CDF8FD8AE90DB473F41EF0B33FA14F";
}
return "";}
I have tried the following also:
if((catName == '1' || catName == '7') && dept == "Entwicklung"){
return "A270AE7F957A74EF0842403EEA0032017567F3E8";
}
and
if(catName == '1' && dept == "Entwicklung"){
return "A270AE7F957A74EF0842403EEA0032017567F3E8";
}
if(catName == '7' && dept == "Entwicklung"){
return "A270AE7F957A74EF0842403EEA0032017567F3E8";
}
It only returns for catName =='1'.
If I understood your problem correctly, I will write your first bit of code as bellow
function _getCatFormGUID(catName) {
var dept = Browser.getValue(getElement("126D81CA203C21CF014C8A3550227892FE4B4A6A"));
if (catName == '1' || catName == '7') {
if(dept == 'Entwicklung'){
return "A270AE7F957A74EF0842403EEA0032017567F3E8";
}
else{
return "8EDD0768A7CDF8FD8AE90DB473F41EF0B33FA14F";
}
}
else{
return "";
}
}
The problem is that you have to understand how those 2 logical operators do the comparison: because your first condition catName == '1' is true, it will never go to second conditions from the first parenthesis nor in the second paranthesis.Given your example, you might rewrite your logical condition from:
if((catName == '1' && dept == "Entwicklung") || (catName == '7' && dept == "Entwicklung")){
return "A270AE7F957A74EF0842403EEA0032017567F3E8";
}
to
if(dept == "Entwicklung" && catName == '1' || catName == '7'){ return something; }
}

Looping through javascript function

I'm trying to loop my if statements inside a while loop through my function. But it will only hit the first if statement and stop looping.
Sample:
while(No.length == 0 || Name.length == 0 || Tel.length == 0
|| Date.length == 0 || Email.length == 0) {
alert("Don't leave blank!");
if (No.length == 0) {
document.getElementById('Nos').style.visibility = 'visible';
return false;
}
if(Name.length == 0) {
document.getElementById('Name').style.visibility = 'visible';
return false;
}
//continues same if statement for rest of the elements variables.
}
It will only go to the first if statement and will not loop through it.
You are returning from inside the loop; that breaks the loop. If you want to continue on to the next round of the loop, use continue instead. If you want to break out of the loop, but not return from the entire function, use break.
Now if you are using a jQuery loop, because it's really just a function, you do use return:
$.each([1,2,3,4], function(index, x) {
if (x < 4) return true; // equivalent to continue
if (x == 4) return false; // equivalent to break
});
but that's only for jQuery loops, not Javascript standard ones.
The first error I can see is you should escape your alert with '\' for example :
alert('Don\'t leave blank!');
And the loop with just continue if you write this :
while(No.length == 0 || Name.length == 0 || Tel.length == 0 || Date.length == 0 || Email.length == 0) {
if (No.length == 0) {
document.getElementById('Nos').style.visibility = 'visible';
}
if(Name.length == 0) {
document.getElementById('Name').style.visibility = 'visible';
}
return true;
}
Could also try:
while(No.length == 0 && Name.length == 0 && Tel.length == 0 && Date.length == 0 && Email.length == 0) {
document.getElementById('Nos').style.visibility = 'visible';
document.getElementById('Name').style.visibility = 'visible';
continue;
}
Maybe this?
function test_all_fields() {
var No = document.getElementById('No');
var Nos = document.getElementById('Nos');
var Name = document.getElementById('Name');
// ...
Nos.style.visibility = (No.value.length==0) ? 'visible':'hidden';
Names.style.visibility = (Name.value.length==0) ? 'visible':'hidden';
//...
//continues same if statement for rest of the elements variables.
if (No.value.length >0 && Name.value.length >0 && Tel.value.length>0 && Date.value.length >0 && Email.value.length>0) {
return true;
}
else {
alert("Don\'t leave blank!");
return false;
}
}

Categories