jQuery / Javascript code check, if not undefined - javascript

Is this code good?
var wlocation = $(this).closest('.myclass').find('li a').attr('href');
if (wlocation.prop !== undefined) { window.location = wlocation; }
or should I do
var wlocation = $(this).closest('.myclass').find('li a').attr('href');
if (wlocation.prop !== "undefined") { window.location = wlocation; }

I like this:
if (wlocation !== undefined)
But if you prefer the second way wouldn't be as you posted. It would be:
if (typeof wlocation !== "undefined")

I generally like the shorthand version:
if (!!wlocation) { window.location = wlocation; }

$.fn.attr(attributeName) returns the attribute value as string, or undefined when the attribute is not present.
Since "", and undefined are both falsy (evaluates to false when coerced to boolean) values in JavaScript, in this case I would write the check as below:
if (wlocation) { ... }

Related

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

Assign empty string to javascript variable

I get return value as null and assign that value it shows as null in the UI. But I want to check some condition and if it is null, it should not show up anything..
I tried the below code and it doesn't work
var companyString;
if(utils.htmlEncode(item.companyname) == null)
{
companyString = '';
}
else{
companyString = utils.htmlEncode(item.companyname);
}
Compare item.companyname to null (but probably really any false-y value) - and not the encoded form.
This is because the encoding will turn null to "null" (or perhaps "", which are strings) and "null" == null (or any_string == null) is false.
Using the ternary operator it can be written as so:
var companyString = item.companyname
? utils.htmlEncode(item.companyname)
: "";
Or with coalescing:
var companyString = utils.htmlEncode(item.companyname ?? "");
Or in a long-hand form:
var companyString;
if(item.companyname) // if any truth-y value then encode
{
companyString = utils.htmlEncode(item.companyname);
}
else{ // else, default to an empty string
companyString = '';
}
var companyString;
if(item.companyname !=undefined && item.companyname != null ){
companyString = utils.htmlEncode(item.companyname);
}
else{
companyString = '';
}
Better to check not undefined along with not null in case of javascript. And you can also put alert or console.logto check what value you are getting to check why your if block not working. Also, utls.htmlEncode will convert your null to String having null literal , so compare without encoding.
var companyString="";
if(utils.htmlEncode(item.companyname) != null)
{
companyString = utils.htmlEncode(item.companyname);
}

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 option handling

What is a better/shorter way to write option handling in JavaScript. Instead of the following pattern?
if(typeof p_options.default_imageset !== "undefined") {
default_imageset = p_options.default_imageset;
} else {
default_imageset = 'mm';
}
Thanks.
You can use something like this:
var default_imageset = p_options.default_imageset || 'mm';
If p_options.default_imageset is truthy (not 0, null, false, '', etc.), the operator short-circuits.
Although usually I do it the other way around:
var value = supplied_value || default_value;

check if html attribute exist and has right value with jquery

Is there a better way for checking an attribute for:
it exist. so value must be false if attribute doesn't exist
Value is correct (boolean)
var isOwner = false;
if ($(selectedItem).is('[data-isOwner="True"]') || $(selectedItem).is('[data-isOwner="true"]')) {
isOwner = true;
} else {
isOwner = false;
}
Now I need to check for 'True' and 'true'...
Thanks
You can convert the value stored in data-isOwner to lower case and only compare the value to 'true'.
if (($(selectedItem).attr ('data-isOwner') || '').toLowerCase () == 'true')
The above use of <wanted-value> || '' will make it so that if the selectedItem doesn't have the attribute data-isOwner the expression will result in an empty string, on which you can call toLowerCase without errors.
Without this little hack you'd have to manually check so that the attribute is indeed present, otherwise you'd run into a runtime-error when trying to call toLowerCase on an undefined object.
If you find the previously mentioned solution confusing you could use something as
var attr_value = $(selectedItem).attr ('data-isOwner');
if (typeof(attr_value) == 'string' && attr_value.toLowerCase () == 'true') {
...
}

Categories