Javascript IF statement with null condition error - javascript

In the following IF statement, one of the conditions is sometimes null.
Parse.User.current() can be null, in which case I'll get this error:
Uncaught TypeError: Cannot read property 'id' of null
Is there an elegant way to avoid this error?
if( post.get("parent").id != Parse.User.current().id ) {
}

A cleaner way can be :
var current = Parse.User.current();
if(current && post.get("parent").id !== current.id ) {
}

Then check like this
if(Parse.User.current() !== null)
{
if( post.get("parent").id !== Parse.User.current().id ) {
//Do whatever necessary
}
}

Related

TypeError: Cannot read property 'hasOwnProperty' of undefined - Twitter API V2 vs. GAS

Twitter API:
https://developer.twitter.com/en/docs/twitter-api/tweets/timelines/introduction
In theory, when there is no data, it should leave the value as empty. As seen in this part of the script:
if (
obj_data.data[int_i].entities.hasOwnProperty("urls") &&
Array.isArray(obj_data.data[int_i].entities.urls) &&
obj_data.data[int_i].entities.urls[0].expanded_url != undefined
) {
array_Expanded_url.push([obj_data.data[int_i].entities.urls[0].expanded_url]);
} else {
array_Expanded_url.push([""]);
}
But this error alert appears:
TypeError: Cannot read property 'hasOwnProperty' of undefined
And the error appears obviously indicating this line:
obj_data.data[int_i].entities.hasOwnProperty("urls") &&
How could I modify my script so that this doesn't happen anymore?
Just check the chain for truthy values
if ( obj_data.data && obj_data.data[int_i] && obj_data.data[int_i].entities && obj_data.data[int_i].entities.urls &&
Array.isArray(obj_data.data[int_i].entities.urls) &&
obj_data.data[int_i].entities.urls[0].expanded_url != undefined)
{ ....
or the more concise (thank you #Scotty Jamison)
if (obj_data.data?.[int_i]?.entities?.urls?.[0]?.expand_url !== undefined) {...
and you can see where things are breaking down
console.log(!obj_data.data, !obj_data.data[int_i], !obj_data.data[int_i].entities, !obj_data.data[int_i].entities.urls);
ex output:
false false true true
Check for null or undefined values
if (
obj_data?.data[int_i]?.entities?.hasOwnProperty('urls') &&
Array.isArray(obj_data?.data[int_i]?.entities.urls) &&
obj_data?.data[int_i]?.entities?.urls[0]?.expanded_url != undefined
) {
array_Expanded_url.push([
obj_data.data[int_i].entities.urls[0].expanded_url,
]);
} else {
array_Expanded_url.push(['']);
}

IF statement to identify 'null' in loop being ignored

I have the following loop which I have put together and is working (up to a point):
for (var i = 0; i < dataIn.length; i++) {
if (dataIn.YourName = [] ) {
var modifiedName = dataIn[i].YourName.replace(/ \([\s\S]*?\)/g, '');
dataIn[i].YourName = modifiedName;
}
else {
console.log('Do Nothing');
}
}
However, I run into an error when the content from the API source is empty (null).
Console error: Cannot read property 'replace' of null
As a result I have tried to update my loop to only run if the information is NOT null or undefined (see below), but it is being ignored and still trying to run.
for (var i = 0; i < dataIn.length; i++) {
if (dataIn.YourName !== null && dataIn.YourName !== '' ) {
var modifiedName = dataIn[i].YourName.replace(/ \([\s\S]*?\)/g, '');
dataIn[i].YourName = modifiedName;
}
else {
console.log('Do Nothing');
}
}
Sample data from the API.
What works:
"YourName": "John Citizen",
What throws the console error:
"YourName": null,
Let's first address an issue here. This line:
if (dataIn.YourName = [] ) {
Will always evaluate true. You are assigning an empty array to your YourName property and then using that assignment in an if - empty arrays are always truthy.
As to how you've tried to correct it, you're checking initially dataIn.YourName but then trying to read dataIn[i].YourName - you need to be consistent. I suspect what you want is:
if (dataIn[i].YourName !== null && dataIn[i].YourName !== '' ) {
var modifiedName = dataIn[i].YourName.replace(/ \([\s\S]*?\)/g, '');
dataIn[i].YourName = modifiedName;
}

Uncaught TypeError: Cannot read property 'get' of null in map function

I have findPlayerWithID function which return matched player id
function findPlayerWithID(players, id) {
let i = 0;
for (; i < players.count(); i++) {
if (players.map((degisken) => degisken.get('id'))._tail === undefined) { continue; }
if (players.map((degisken) => degisken.get('id'))._tail.array[i] === id) {
return i;
}
}
return -1;
}
But sometimes it give error in this line
if (players.map((degisken) => degisken.get('id'))._tail === undefined) { continue; }
error is
gameStore.js:38 Uncaught TypeError: Cannot read property 'get' of null
at gameStore.js:38
at immutable.js:3018
at Ue.__iterate (immutable.js:2208)
at r.__iterateUncached (immutable.js:3017)
at F (immutable.js:606)
at r.T.__iterate (immutable.js:322)
at r.toArray (immutable.js:4260)
at new Ue (immutable.js:2067)
at _t (immutable.js:3572)
at Ue.map (immutable.js:4403)
I think error because of null object
How can I check null in this line
if (players.map((degisken) => degisken.get('id')).
immutable.js:1317 Uncaught TypeError: Cannot read property 'merge' of null
at immutable.js:1317
at Ne (immutable.js:1973)
at Ne (immutable.js:1982)
at Ne (immutable.js:1982)
at pe.updateIn (immutable.js:1280)
at pe.mergeIn (immutable.js:1314)
at gameStore.js:207
at createReducer.js:15
at combineReducers.js:133
at c (createStore.js:178)
Updated
with #canaan-seaton answear I change
this
if (players.filter(degisken => degisken !== null).map((degisken) => degisken.get('id'))._tail.array[i] === id) {
return i;
}
this work
but it give another error in immutablejs
Uncaught TypeError: Cannot read property 'merge' of null
at immutable.js:1317
at Ne (immutable.js:1973)
at Ne (immutable.js:1982)
at Ne (immutable.js:1982)
at pe.updateIn (immutable.js:1280)
at pe.mergeIn (immutable.js:1314)
at gameStore.js:207
at createReducer.js:15
at combineReducers.js:133
at c (createStore.js:178)
at this line in immutablejs
function(m ) {return typeof m.merge === 'function' ?
I searcg for that error
there is some info but I don't understand what should I do https://github.com/facebook/immutable-js/issues/597
here is my console
Generally , it is not a good practice to check for equality to undefined.
I would try to do it this way:
First of all, to make sure that degisken does exists you can go with degisken && degisken.get(id)
Second, you might want to use Object's hasOwnProperty method, which will be useful in here:
players.map((degisken) => {
const id = degisken && degisken.get('id');
if(id && id.hasOwnProperty('_tail') && id._tail.array[i] === id){
return i
}
});
if you just want to check if the array has elements then you can do something like the following....
if (players && players.length > 0) {/* Do Stuff */}
if you are concerned with specific indices within the array being null then you could do something like this....
if (players.filter(degisken => degisken !== null)
.map((degisken) => degisken.get('id'))._tail === undefined)
{/* Do Stuff */}

Can't seem to catch javascript being null

I have the following code, and i'm trying to protect when an error happens / no data is returned. As it stands, I get the error:
[Info] undefined (ionic.bundle.js, line 19387)
[Error] Error: undefined is not an object (evaluating 'data.data.length')
The code is like the following, understandably it's falling over because data.data.length is null / undefined (no data returned on purpose to test)
SaveSubmitService.saveLocal('GetData', 'NearByHubs4S', $scope.options, false).then(function (data) {
$scope.return = data;
if (typeof data != "undefined") {
if (data.data.length > 0) {
$scope.bars = $scope.return.data;
$scope.noNot = false;
} else {
$scope.noNot = true;
}
} else {
$cordovaDialogs.alert('Could not retrieve data. Are you sure you\'re online?', 'No Response', 'Ok');
}
$scope.$broadcast('scroll.refreshComplete');
});
Oddly, it's going through the typeof as true and falling over at data.data.length being null.
I've tried doing if data == null, data == undefined, data == "undefined", data.data.length == undefined etc.
Basically i'm trying to error if the length is null!
The problem is not that data.data.length is null. The problem is that you want to use length property on undefined. That means that data is defined and non-null, but it does not have a data property, so data.data is undefined.
Instead of:
if (typeof data != "undefined") {
if (data.data.length > 0) {
Do:
if (data && data.data) {
if (data.data.length > 0) {
It looks to me like your guard isn't sufficient, you need to check data and also data.data:
$scope.return = data;
if (data && data.data) {
if (data.data.length > 0) {
$scope.bars = $scope.return.data;
$scope.noNot = false;
} else {
$scope.noNot = true;
}
} else {
$cordovaDialogs.alert('Could not retrieve data. Are you sure you\'re online?', 'No Response', 'Ok');
}
The guard data && data.data will only be true if data is truthy (any value other than null, undefined, 0, "", NaN, or false, which are all falsy) and also if data.data is truthy. It won't try to check data.data if data is falsy.
You seem to be only checking the data variable, and not its data member.
Try using an if statement such as if (data && data.data & data.data.length > 0) to check for null data.
Try this
if (data && data.data) {
if (data.data.length > 0) {
...
} else {
....
}
}

Check two variables for undefined

JS:
var ctoken = req.cookies.user;
var stoken = req.session.passport.user;
if(ctoken === 'undefined' || stoken === 'undefined'){
return res.send('invalid token');
}else{
if (ctoken.split('_')[0] !== stoken) {
return res.send('invalid token');
}
}
At
ctoken.split('_')[0]
an error is thrown :
cannot call split of undefined.
Why? This should not happen because of the if condition.
Remove the quotes :
if (ctoken === undefined || stoken === undefined) {
Maybe you were confused by a trend during which some programmers recommended to test using
if (typeof something === 'undefined') {
But the best test is to simply compare with undefined.

Categories

Resources