.toLocaleString() come as undefined - javascript

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

Related

Use query input for if statement condition

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

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

|| operator not setting default when null

I am running this line:
var good = data["good"] || false;
where data comes from the success method in a jquery ajax request.
But, what I thought that this would do is default good to false if data["good"] is null, but it is not.
Chrome is throwing this:
Uncaught TypeError: Cannot read property 'good' of null
and since it is null, shouldn't good then be set to false?
The problem is not that data["good"] is null, but that data itself is null.
Your code as is would be fine if data always has a value, but may not have property good. But unfortunately the JavaScript engine doesn't check if everything in a statement is undefined or null, i.e. it won't test data, and then test data["good"] and so on.
You need to test if data has at least some sort of value first, that is, it is "truthy".
Fix 1
You can lay it out clearly like so:
var good = false;
if(data && data["good"]) {
good = data["good"];
}
Fix 2
Or a neat shortcut is to use the fact that && and || will return the first "truthy" value found - it does not have to be a boolean:
var good = (data && data["good"]) || false;
The jquery tutorial on Operators has a good explanation of what is returned from the && and || operators.
// has a value - sets to "foo"
var data1 = { good: 'foo' };
var good1 = (data1 && data1["good"]) || false;
document.write("<div>" + good1 + "</div>");
// data is null - sets to false
var data2 = null;
var good2 = (data2 && data2["good"]) || false;
document.write("<div>" + good2 + "</div>");
// data["good"] doesn't exist - sets to false
var data3 = { bad: 'hello' };
var good3 = (data3 && data3["good"]) || false;
document.write("<div>" + good3 + "</div>");
Falsy Gotchas!
The other thing to be careful of is that some values you would want to store in your variable may evaluate to false, so you might incorrectly end up with good = false. This depends on what you expect to be inside data["good"].
This will occur for the following, again from the jquery site:
false - boolean false value
"" - Empty strings
NaN - "not-a-number"
null - null values
undefined - undefined values (i.e. if data doesn't have property "good")
0 - the number zero.
If you think this could be the case, you may need to be more specific in your checks:
var data = { good: 0 };
// 0 is falsy, so incorrectly sets to false
var good = (data && data["good"]) || false;
document.write("<div>" + good + "</div>");
// check the actual type and value - correctly set to 0
var good2 = (data && (typeof data["good"] != "undefined") && data["good"] != null)
? data["good"] : false;
document.write("<div>" + good2 + "</div>");
In your case, I can't imagine one-liner, which will check if data is not null and if so, put data[good] into variable.
You must first of all, get rid of Exception.
I would rather do:
var good = false;
if(data){
good = data["good"] || false;
}

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');

javascript null value not working

here's my function for checking zipcode. When a null values comes in, i keep getting "Object Required" Does anyone know where im going wrong?
aspx tags -
asp:CustomValidator
ID="cv_zipcode"
runat="server"
ControlToValidate="tb_zipcode"
ClientValidationFunction="ValidateZipcode"
ValidateEmptyText="true"
Display="Dynamic"
ValidationGroup="vgroup">
</asp:CustomValidator>
function ValidateZipcode(sender, args) {
var regZipcode = '\d{5}'
var zipcode = document.getElementById(sender.id.replace(/cv_/, "tb_"));
if ((zipcode.value == "ZipCode") || (zipcode.value.length == null) || (zipcode.value.length == "")) {
zipcode.style.backgroundColor = "#f6e086";
args.IsValid = false; return;
} else {
args.IsValid = true;
zipcode.style.backgroundColor = "white";
}
}
I'm not sure exactly which value is null, but in general, if you have a variable x which may or may not be null, and you want to do something with x, you can do the following:
x != null && do_something_with(x)
If x == null, then this returns false and doesn't try to execute do_something_with(). Otherwise, this expression returns the value of do_something_with(x).
If you just do_something_with(x), and x is null, and do_something_with() is not expecting a null, you can get errors.
EDIT:
try:
if ((zipcode == null) || (zipcode.value == null) || [everything else])
zipcode.value.length returns an integer
I think you should have
if ((zipcode.value == "ZipCode") || (zipcode.value.length == 0))
I would be a little suspect of this line:
if ((zipcode.value == "ZipCode") || (zipcode.value.length == null) || (zipcode.value.length == "")) {
Try this instead:
if ((zipCode.value == null) || (zipcode.value== "") || (zipcode.value.length == 0)) {
That error message usually indicates that you've tried to get or set a property or call a method of something that isn't an object, which tends to happen when a variable that you thought referred to an object is actuall null or undefined. That is, if someVariable is null or undefined then you can't say someVariable.someProperty.
If .getElementById() doesn't find a matching element it returns null, so in this line:
var zipcode = document.getElementById(sender.id.replace(/cv_/, "tb_"));
zipcode is potentially set to null, and if it is then all attempts to access properties of zipcode like zipcode.value and zipcode.style will fail.
If the parameter args comes in as null or undefined then attempting to set args.IsValid will fail, and similarly if the parameter sender is null or undefined then sender.id will fail.
So, if you have a variable that might be null you should test that before trying to do anything else with it.

Categories