Why does my if not pass in the else? - javascript

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.

Related

Check for multiple cases without if statement in 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'))

Create RegEx control for URL

I have a problem with my current web application. Indeed, when I put the current link : https://localhost:44311/#shop, my page displayed perfectly. Here a picture :
But then when I try to change my URL to : https://localhost:44311/#/ , to verify the control of the redirection, the content displayed into the same content, here a picture of what happened :
Currently, all my ajax calls are called again and again and again (an infinite loop).
I'm trying to add control regex for #/, and try to respect #/xxxx/xxxxx. But without success. If you can help me, it could be very nice !
Here my JS where I manage the loadpages :
var ui = {
controller: {
page: {}
},
component: {
category: null
}
};
ui.controller.pageLoad = function (hash = null) {
if (hash === null) {
hash = window.location.hash;
if (hash.length < 2 || hash[0] !== "#") {
hash = "/shop";
}
} else if (hash.length < 2 || hash[0] === "#" && hash[1] === '/') { // add control regex for #/, must respect #/xxxx/xxxxx
hash = "/shop";
}
$.get(hash.substring(1), function (data) {
ui.controller.page = null;
$("#content").html(data);
}).fail(function (error) {
$.get("/Home/Error?status=" + error.status, function (data) {
ui.controller.page = null;
$("#content").html(data);
});
});
};
You could create a isValidHash function, and use it in your if statement:
function isValidHash(hash) {
return typeof hash === "string" && /^#(\/[a-z0-9-]+)+$/.test(hash);
}
function test(v) {
console.log(`'${v}' is ${isValidHash(v) ? '' : 'NOT '}valid`);
}
test(null); // NO - not a string
test('#'); // NO - too short
test('#shop'); // NO - no slash
test('#/shop'); // YES
test('#/shop/item-9'); // YES

If external file doesn't exist file is stopped: is possible to solve this?

Sorry for title but is difficult to explain this...
I have external javascript file with inside there's a variable (var eui)
My code is run if this variable exist and if is not exist alert something.
if((eui != 000) || (eui !== null) || (typeof eui !== 'undefined')){
alert('ok');
}
else{
alert('not exist file');
}
In my case, with console, i read that eui is not defined and second alert is not print.
Why ?
How can i solve this?
Looks like your condition in if-statement is incorrect. I think this one might work better:
if ((typeof eui !== 'undefined') && (eui !== null) && (eui != 000)) {
alert('ok');
} else {
alert('not exist file');
}
So you first need to check if eui is properly defined and proceed with other checks only if it's true. It means that you want to use && operators (AND condition, not OR).

Javascript IF statement with null condition error

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

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