Check for multiple cases without if statement in JavaScript - javascript

I created this function which should check for every case, and if one of the case not corresponding then i should get immediately the result.
const addText = (data, addAlternative) => {
return (data !== 'N/T' || data === 0 || data) ? data : addAlternative;
};
console.log(addText('N/T', 'alternative'))
in my case addText('N/T', 'alternative') i get N/T, but i expect to get alternative word as a result. How to change my statement to check every situation and if one of the situation occurs i have to get the right answer like in the example that i provided?

You are receiving NT as output, because you are checking the truthy status of data parameter isiide the function by using data !== 'N/T' || data === 0 || data.
Update that to data !== 'N/T' || data === 0, it will work as expected.
const addDefaultTextIfIsEmpty = (data, addAlternative) => {
return (data !== 'N/T' || data === 0) ? data : addAlternative;
};
console.log(addDefaultTextIfIsEmpty('N/T', 'alternative'))
If you want to output data if the param is not defined, just check !data inside the condition, there you dont need to add data === 0 because !data will handle null, undefined, empty, and zero checks
const addDefaultTextIfIsEmpty = (data, addAlternative) => {
return (data !== 'N/T' || !data) ? data : addAlternative;
};
console.log(addDefaultTextIfIsEmpty('N/T', 'alternative'))

You need to prevent if (data) from being tested if data is 'N/T' but currently it is being evaluated at the end because of short-circuiting.
Your logic is basically:
return (false || false || true) ? ...
^ ^ \____ because data contains 'N/T'
| |
| '-------- data is not 0
because data is N/T
This obviously resolves to true because the || operator only needs one of the expressions to be true.
What you actually want is:
return (data !== 'N/T' && (data === 0 || data)) ? ...
^
|
remember De-Morgan's Theorem
(google it if you don't know)

const addText = (data, addAlternative) => {
return (data !== 'N/T' || data === 0) ? data : addAlternative;
};

const addText = (data, addAlternative) => {
return ((data && data !== 'N/T') || data === 0) ? data : addAlternative;
};
console.log(addText('N/T', 'alternative'))

/* Try below */
const addDefaultTextIfIsEmpty = (data, addAlternative) => {
return (data !== 'N/T' || data === 0) ? data : addAlternative;
};
addDefaultTextIfIsEmpty('N/T', 'alternative')

You are using data in if statement and you are passing 'N/T' which changes the value to false and according to the logic the value always be true. Try this solution.
const addText = (data, addAlternative) => (data && (data !== 'N/T' || data === null || data === 0)) ? data : addAlternative;
console.log(addText('N/T', 'alternative'))

Related

NodeJS crashes after sometime of leading a csv file

I've been working on a project that outputs xml upon reading a csv, I use the fs.createReadStream() method to read the csv file but after some time, the terminal just crashes.
And I get
C:\Users\username\Documents\Programming\Node Projects\DAE Parser\main.js:13
row["Value"].includes("tri") ||
^
TypeError: Cannot read property 'includes' of undefined
It doesn't read the whole file.
here's what i'm doing
fs.createReadStream("test.csv")
.pipe(csv())
.on("data", row => {
if (
row["Value"].includes("tri") ||
row["Value"].includes("vt") ||
row["Value"].includes("vx") ||
row["Value"].includes("vn")
) {
console.log(row)
}
})
Your row["Value"] is undefined, you can add a condition to check if it's falsy
fs.createReadStream("test.csv")
.pipe(csv())
.on("data", row => {
if (row["Value"] && (
row["Value"].includes("tri") ||
row["Value"].includes("vt") ||
row["Value"].includes("vx") ||
row["Value"].includes("vn")
)) {
console.log(row)
}
})
Your code is vulnerable in cases where:
row is not an object
row["Value"] does not exist or is not an array.
If you want to be completely safe against these in any particular row, then you can do this:
fs.createReadStream("test.csv")
.pipe(csv())
.on("data", row => {
if (typeof row === "object") {
let arr = row.Value;
if (arr && Array.isArray(arr) && (
arr.includes("tri") ||
arr.includes("vt") ||
arr.includes("vx") ||
arr.includes("vn")
)) {
console.log(row);
}
}
})

Why does my if not pass in the else?

I do an if to do an ajax query. If my string 'page' is undefined or does not contain the word 'page =', I want to execute my ajax query.
I specify that the variable page (which is a "href"), changes every time the ajax query is generated.
var page = $(this).attr('href');
If not, I want to go into my 'else'.
Can you tell me what is wrong? I'm lost.
if (typeof page !== 'undefined' || page.search('page=') !== -1 ){
$.ajax({
url: page,
beforeSend: function () {
button.addClass('loading');
},
success: function (data) {
$('.former-students__list').append(data.students);
button.attr('href', data.next_page);
button.removeClass('loading');
w.ajaxGraduated.initGrid();
},
})
} else {
button.addClass('finish');
button.attr(href, '');
$('.load-more__label-text').text('Vous avez tout vu !');
}
I believe it should be an AND condition and not an OR:
if ((typeof page !== 'undefined') && (page.search('page=') !== -1 )) {
If you want the if block to run when
'page' is undefined or does not contain the word 'page ='
then you should use "===" for the first condition and not "!==".
if (typeof page === 'undefined' || page.search('page=') !== -1 ){
have you tried using normal operator == or != inside if statement?
if (typeof page != 'undefined' || page.search('page=') != -1 ){
and, as Eldad commented, I think you should use an AND as if the typeof is not undefined it will enter the if in any case, no matter the page.search.

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.

check that a collection is not empty

How do you check that data.results in the following is not empty before trying to perform actions on it?
$.getJSON(myurl, function(data) {
// if data.results is not empty
// {
// console.log(data.results.size);
// }
});
if (data != null && data.results != null && data.results.length > 0) {
// the array is not empty
}
I usually use something like this:
if (data != null && data.results != null && data.results.size != 0) ...
how about doing this one?
if(data!=undefined){
// do logic here
}

Categories

Resources