Check two variables for undefined - javascript

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.

Related

Receiving error message when initialising JavaScript function

So below is my javascript code. It's wrapped in module.exports, but that's not the error.
parseMention = (arg, asId = false) => {
if(!arg.startsWith('<#') && arg.endsWith('>')) return undefined
let id = arg.slice(2, -1)
if(id.startsWith('!')) id.slice(1)
if(asId === true) return id
if(asId === false) return bot.users.cache.get(id)
}
despite it seeming correct to me, I get the following error message:
SyntaxError: Invalid shorthand property initializer
Any help would be much appreciated
It's wrapped in module.exports, but that's not the error.
I'm pretty sure there is the error.
This part of your code won't throw a SyntaxError: Invalid shorthand property initializer error. It would be great to see your module.exports, but it's 99.9% that you're trying to export an object like this and the = after parseMention is an invalid shorthand property initialiser:
// This is invalid syntax
module.exports = {
parseMention = (arg, asId = false) => {
if (!arg.startsWith('<#') && arg.endsWith('>')) return undefined;
let id = arg.slice(2, -1);
if (id.startsWith('!')) id.slice(1);
if (asId === true) return id;
if (asId === false) return bot.users.cache.get(id);
}
}
This should work:
module.exports = {
parseMention(arg, asId = false) {
if (!arg.startsWith('<#') && arg.endsWith('>')) return undefined;
let id = arg.slice(2, -1);
// it won't do anything, slice won't mutate id and you don't return
if (id.startsWith('!')) id.slice(1);
if (asId === true) return id;
if (asId === false) return bot.users.cache.get(id);
},
};

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.

Why does my function not return the error string?

I have function below. It does what it needs to except that it does not return the error string I want.
It always returns "".
I've put breakpoints and seen it step into each error case, but it doesn't return there. It returns at the end of the function.
I'm lost, I'm sure I'm making a really stupid mistake but I don't get it...
Save me the few hairs I have please :)
public validatePanel = () => {
this.Queries().forEach(function(q, i) {
if(q.from() == "" || q.from() == null || q.from() == undefined) {
return "Please select a database";
}
if(q.select().length > 0) {
q.select().forEach(function(s, j) {
if(s.selectoption() == "" || s.selectoption() == null || s.selectoption() == undefined){
return "Please select a stat to show";
}
});
}
if(q.where().length > 0) {
q.where().forEach(function(w, j) {
if(w.whereoption() == "" || w.whereoption() == null || w.whereoption() == undefined){
return "Please select a filter to filter on";
}
if(w.wherevalue() == "" || w.wherevalue() == null || w.wherevalue() == undefined) {
return "Please select a value for your filter";
}
});
}
});
return "";
}
As pointed out by Alex Bykov, your forEach function is not causing a return.
Your question on why not, per the MDN
The return value of the function is undefined
Return
value undefined.
Which means nothing you can do will generate a return value you can use. Also per the MDN there is no way to stop or break the loop other than throwing an exception.
There is no way to stop or break a forEach() loop other than by
throwing an exception. If you need such behavior, the forEach() method
is the wrong tool, use a plain loop instead. If you are testing the
array elements for a predicate and need a Boolean return value, you
can use every() or some() instead. If available, the new methods
find() or findIndex() can be used for early termination upon true
predicates as well.
Which means you will need to throw your exception in the forEach loop and then catch the exception and return the string like below
(unless you use a normal for loop then you can do whatever you please)
try {
this.Queries().forEach(function(q, i) {
if(q.from() == "" || q.from() == null || q.from() == undefined) {
throw "Please select a database";
}
if(q.select().length > 0) {
q.select().forEach(function(s, j) {
if(s.selectoption() == "" || s.selectoption() == null || s.selectoption() == undefined){
throw "Please select a stat to show";
}
});
}
if(q.where().length > 0) {
q.where().forEach(function(w, j) {
if(w.whereoption() == "" || w.whereoption() == null || w.whereoption() == undefined){
throw "Please select a filter to filter on";
}
if(w.wherevalue() == "" || w.wherevalue() == null || w.wherevalue() == undefined) {
throw "Please select a value for your filter";
}
});
}
});
}
catch(err) {
console.log(error);
}

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 JavaScript variable null or not?

Iam using following lines of code to check whether the JS variable 'userName' is null or not.
But am always getting alert "not empty"
Please check my onready method:
$("document").ready(function (){
var userName = "";
if (userName == undefined || userName == null) {
alert('empty');
} else {
alert('not empty');
var div = document.getElementById('title b');
div.innerHTML = div.innerHTML + ',';
}
});
You need typeof keyword to check it's type. !userName will take care of the rest, like null or empty values.
if ( typeof userName === 'undefined' || !userName ) {
alert('empty');
}
You're setting var userName to "". It will never be null.
Declare your variable as var userName;, instead of var userName = "";
However, unless you actually do something with userName, the if / else will be pretty pointless.
No your variable is neither undefined nor null.
What you could do though is this replace this line
if (userName == undefined || userName == null) {
by this line
if (!userName) {
Empty string is not null nor undefined.
You can check using the ! operator:
if (!userName) {
// Do the stuff
}
For completeness:
!"" == true
!null == true
!undefined == true
!"hi" == false
Note that:
!0 == true
!1 == false
!"0" == false
!"1" == false
Try
var userName = "";
if (userName.length < 1) {
alert('empty' +"\n"+ userName.length);
} else {
alert('not empty');
var div = document.getElementById('title b');
div.innerHTML = div.innerHTML + ',';
}

Categories

Resources