Use query input for if statement condition - javascript

I am doing a mini-API on Express.
On an request, I want to verify that all the query parameters are filled.
Hence, my intuition led me to this:
app.get("/book", (req, res) => {
console.log(req.query.seats, req.query.category, req.query.date);
let isEmpty =
req.query.seats === undefined ||
req.query.category === undefined ||
req.query.date === undefined;
console.log(isEmpty);
if (isEmpty === true) {
console.log("here3");
res.status(400).send("Missing input");
}
// else continue with instructions
}
Nevertheless, the console outputs false for isEmpty, while it tells that elements (req.query.category) is undefined, passing to the next instruction and not catching the error.
Does the elements have a different behavior in a console log and and comparison ?
thanks !

If you want to check for undefined AND empty string without problem you could do this way :
let isEmpty = !req.query.seats || !req.query.category || !req.query.date
For example :
var seats = '';
var category = undefined;
var date = '';
let isEmpty = !seats || !category || !date
console.log(isEmpty) // true

Related

.toLocaleString() come as undefined

So I wrote a code that gets information from https://api.hypixel.net/ which is in JSON,
var wolfxpp = response10.data.profile.members[uuis].slayer_bosses.wolf.xp.toLocaleString()
If a user doesn't have XP .toLocaleString comes as undefined
How can I fix that and make it on embed as '0'
I tried
if (response10.data.profile.members[uuis].slayer_bosses.wolf.xp == undefined) {
return wolfxpp = '0';
}
The error stopped showing after this but the embed still haven't been sent
How can I define an undefined value?
return wolfxpp = '0'; is not how it works
You could do this
wolfxpp = response10.data.profile.members[uuis].slayer_bosses.wolf.xp;
if (wolfxpp === undefined) wolfxpp = '0';
This is simpler:
var wolfxpp = (response10.data.profile.members[uuis].slayer_bosses.wolf.xp || 0).toLocaleString()
If there is no xp, use 0 instead. The (var || 0) is testing for any falsy value and returns 0 if falsy

How do I handle indexOf returning 'null' without using try/catch(err)?

I'm populating a table with data - using fixed-data-table, which is a React.js component. However, that isn't so important at this stage.
The table has a search box where the issue stems from.
First, here's the interesting part of the code.
for (var index = 0; index < size; index++) {
if (!filterBy || filterBy == undefined) {
filteredIndexes.push(index);
}
else {
var backendInfo = this._dataList[index];
var userListMap = hostInfo.userList;
var userListArr = Object.values(userListMap);
function checkUsers(){
for (var key in userListArr) {
if (userListArr.hasOwnProperty(key) && userListArr[key].text.toLowerCase().indexOf(filterBy) !== -1) {
return true;
}
}
return false;
}
if (backendInfo.firstName.indexOf(filterBy) !== -1 || backendInfo.lastName.toLowerCase().indexOf(filterBy) !== -1 || backendInfo.countryOrigin.toLowerCase().indexOf(filterBy) !== -1
|| backendInfo.userListMap.indexOf(filterBy) !== -1) {
filteredIndexes.push(index);
}
}
}
This is rendered and the last part is throwing errors if you input something in the table, and a column returns null from the user input.
The thing is, I can make the code work if I change the last part to ..
try {
if (backendInfo.firstName.indexOf(filterBy) !== -1 || backendInfo.lastName.toLowerCase().indexOf(filterBy) !== -1 || backendInfo.countryOrigin.toLowerCase().indexOf(filterBy) !== -1
|| backendInfo.userListMap.indexOf(filterBy) !== -1) {
filteredIndexes.push(index);
}
}
catch(err) {
console.log('Exception')
}
With the try/catch, it works 100% as intended and handles the indexOf returning null... But this can't be the way to properly handle it - I'm assuming this sort of exception handling is, well, supposed to be for rare exceptions, and shouldn't really be used on the front-end as much as the backend.
How do I handle indexOf returning null in the above Javascript code? It might return null in any of the sources columns that are being populated.
If a key cannot be found, JS will throw an error. Try-catch is a good way to fix these errors, but there is an alternative:
You could check if keys exist in an object prior to pushing a value into it.
var data = { };
var key = "test";
// your method works great
try {
var value = data.firstname.indexOf(key);
} catch (err) {}
// another method, I'd prefer the try/catch
var value = data.firstname ? data.firstname.indexOf(key) : undefined;
// test if the object is the type of object you are looking for
// this is in my opinion the best option.
if(data.firstname instanceof Array){
var value = data.firstname.indexOf(key);
}
// you can use the last option in your code like this:
var firstnameHasKey = data.firstname instanceof Array && ~data.firstname.indexOf(key);
var lastnameHasKey = data.lastname instanceof Array && ~data.lastname.indexOf(key);
if(firstnameHasKey || lastnameHasKey){
// logics
}
If you test the instanceof && indexOf, there will never be an error. If firstname is undefined, the indexOf will never be checked.
Ofcourse you can use this for other types:
var myDate = new Date();
myDate instanceof Date; // returns true
myDate instanceof Object; // returns true
myDate instanceof String; // returns false
MDN documentation

Javascript setting variable to result or nothing

See javascript comments
var SearchResult = {
googleApiKey: "",
googleUrl: "https://www.googleapis.com/shopping/search/v1/public/products?key={key}&country={country}&q={query}&alt=atom",
country: "UK"
Query: function( args )
{
// Is there a way to do this in a less messy way?
args.googleApiKey ? : this.googleApiKey = args.googleApiKey : null;
args.country? : this.country = args.country: null;
}
}
Basically, if someone supplies a new value for my object properties, I want it to set it, otherwise just continue using the default values supplied.
I'm aware of bitwise operators being good for option selecting but I don't know how I would port that into javascript?
args.googleApiKey = args.googleApiKey || this.googleApiKey;
args.country = args.country || this.country;
Not sure I understood your question;
In JavaScript you can use the following:
// thingYouWantToSet = possiblyUndefinedValue || defaultValue;
this.googleApiKey = args.googleApiKey || '';
The caveat to using this is that if the first value is a zero or empty string, you will end up using the default value, which may not be what you intend. e.g.
var example = '';
var result = example || 'default';
Although example is set, you will end up with the 'default' string. If this causes issues for you, switch to:
(typeof args.googleApiKey === 'undefined')
? this.googleApiKey = 'default'
: this.googleApiKey = args.googleApiKey;
You could make this cleaner using a helper function if you are repeating yourself a lot.
var mergedSetting = function (setting, default) {
return (typeof setting === 'undefined') ? default : setting;
}
this.googleApiKey = mergedSetting(args.googleApiKey, 'default value');

Common error message in JavaScript

AddPatient = {};
AddPatient.Firstname = FirstNameValue || PatientModel.errorMsg('FirstName',FirstNameValue);
AddPatient.LastName = LastNameValue || PatientModel.errorMsg('LastName',LastNameValue);
AddPatient is an Object and i am checking it whether its blank or not before sending the request.
PatientModel.js
errorMsg: function(title,FirstNameValue,LastNameValue) {
if(FirstNameValue === undefined || FirstNameValue === ' ' && LastNameValue === undefined || LastNameValue = ' ') {
alert('FirstName and LastName are missing');
return false;
} else {
alert(+title 'is missing');
return false;
}
}
I have a form, where i have FirstName and LastName field and i have to check it should not be blank. I want a single function in javascript which can work.
Is this the right way to do it?
I can see a couple of problems in your code.
Mismatch between errorMsg()'s expected arguments and how it is called
Syntax error in second alert()
Bad expression inside if statement
Mismatch between errorMsg()'s expected arguments and how it is called
Your errorMsg() function expects three arguments, but you only pass it two at a time:
errorMsg: function(title,FirstNameValue,LastNameValue) {
....
}
... and then ....
.errorMsg('FirstName',FirstNameValue);
.errorMsg('FirstName',LastNameValue);
If you really want to use both values inside errorMsg(), you need to pass them both every time, in the same order the function expects them:
PatientModel.errorMsg('FirstName',FirstNameValue,LastNameValue);
PatientModel.errorMsg('LastName',FirstNameValue,LastNameValue);
// This is weird code, but it'll work
Syntax error in second alert()
This is simple enough to fix, and could have been just a typo.
alert(+title 'is missing');
^ ^_There's something missing here.
|_This will only try to convert title to a number
What you want is this:
alert(title + 'is missing');
Bad expression inside if statement
if(FirstNameValue === undefined || FirstNameValue === ' ' && LastNameValue === undefined || LastNameValue = ' ') {
This won't work as you expect, because && has greater precedence than ||, meaning the expression will be evaluated as such:
if (
FirstNameValue === undefined
|| (FirstNameValue === ' ' && LastNameValue === undefined)
|| LastNameValue = ' '
) {
You would need parenthesis to fix the precedence:
if( (FirstNameValue === undefined || FirstNameValue === ' ') && (LastNameValue === undefined || LastNameValue = ' ') ) {
This is irrelevant, actually, because the expression can be simplified like this:
// If these values are taken from a form input, they are guaranteed to be strings.
if(FirstNameValue.length === 0 && LastNameValue.length === 0) {
Or even better, like this:
// Uses regular expressions to checks if string is not whitespace only
var WHITESPACE = /^\s*$/;
if( WHITESPACE.test(FirstNameValue) && WHITESPACE.test(FirstNameValue)){
How I would fix your code
This would be an incomplete answer if I didn't provide a correct version of your code, so here it goes. Notice that I separate filling-in of information and its validation in two steps.
PatientModel.js :
validate: function(patient){
var WHITESPACE = /^\s*$/;
var errors = [];
if( WHITESPACE.test(patient.FirstName) ){
// No first name
if( WHITESPACE.test(patient.LastName) ){
// No last name either
errors.push('FirstName and LastName are missing');
}
else {
// Only first name missing
errors.push('FirstName is missing');
}
}
else if( WHITESPACE.test( patient.LastName) ){
// Only last name missing
errors.push('LastName is missing');
}
// Returns array of errors
return errors;
}
Your other code:
AddPatient = {};
AddPatient.Firstname = FirstNameValue;
AddPatient.LastName = LastNameValue;
errors = PatientModel.validate(AddPatient);
if( errors.length != 0 ){
alert('You have the following errors:\n' + errors.join('\n'));
}
Edit: a different, perhaps better, approach. The only difference is we now write validate() as a method of a Patient object:
>>> PatientModel.js:
var WHITESPACE = /^\s*$/;
// Creates a new empty Patient
function Patient(){
this.FirstName = '';
this.LastName = '';
}
// Adds a validate() method to all Patient instances
Patient.prototype.validate: function(){
var errors = [];
if( WHITESPACE.test(this.FirstName) ){
// No first name
if( WHITESPACE.test(this.LastName) ){
// No last name either
errors.push('FirstName and LastName are missing');
}
else {
// Only first name missing
errors.push('FirstName is missing');
}
}
else if( WHITESPACE.test( thisLastName) ){
// Only last name missing
errors.push('LastName is missing');
}
// Returns array of errors
return errors;
}
>>> Your other code :
patient = new Patient();
patient.FirstName = FirstNameValue;
patient.LastName = LastNameValue;
errors = patient.validate();
if( errors.length != 0 ){
alert('You have the following errors:\n' + errors.join('\n'));
}
I would recommend using the Jquery validate plugin for this functionality. It will let you do a hole range of clientside validation. Including required validation.
If you just want pure javascript then your method is fine. I'd make it a more generic validate method which would check each validation rule you have and if it fails add the message to an array. After all your checks are finished if the count of the array is grater then zero then output complete list of errors.

Check JSON data structure for existance of lower level names

Can I use 'in' to check existence of non top level names in a JSON data structure in a single comparison?
I have n tier JSON data structures,
I can do: if("mbled" in jsonData), works fine
For a lower tier name:
I can do this but (works but gets clunky as I go deeper): if("pnpenvsense1" in jsonData && "light" in jsonData.pnpenvsense1)
I'd prefer something like (doesn't work, always returns false): if("pnpenvsense1.light" in jsonData)
something like:
function objExists(path, struct){
path = path.split('.');
for(var i=0, l=path.length; i<l; i++){
if(!struct.hasOwnProperty(path[i])){ return false; }
struct = struct[path[i]];
}
return true;
}
objExists('pnpenvsense1.light', jsonData);
try
// will check if it is defined and not false
if(pnpenvsense1.light !== undefined && pnpenvsense1.light != false )
{ // my code }
http://jsfiddle.net/
arr = new Array();
arr['myKey'] = 12;
arr['myOtherKey'] = { "first" : "yes" , "second" : false };
if(arr.myKey !== undefined && arr.myKey != false)
alert("1 -> " + arr.myKey);
if(arr.myOtherKey.first !== undefined && arr.myOtherKey.first != false)
alert("2 -> " + arr.myOtherKey.first);

Categories