I have an object with multiple properties, each property has a value that is a string. When I try to concatenate the values of each property, it returns NaN.
var urlProps = {
searchTerm: "searchSTUFF",
baseURL: "https://en.wikipedia.org/w/api.php?action=query&prop=extracts&format=json&exsentences=1&exlimit=10&exintro=&explaintext=&titles=%20&generator=search&gsrsearch=",
tailURL: "&rawcontinue=&callback=?",
finalURL: this.baseURL + this.searchTerm + this.tailURL
}
console.log(urlProps.finalURL);
//NaN
What am I doing wrong here, or what is the proper way of doing this?
JavaScript uses NaN as the result of a failed operation on numbers including: Parsing numbers. Using undefined as an operand. Using NaN as an operand.
NaN is a property of the global object. In other words, it is a variable in global scope. The initial value of NaN is Not-A-Number — the same as the value of Number. NaN . In modern browsers, NaN is a non-configurable, non-writable property.
In JavaScript, NaN is short for "Not-a-Number". In JavaScript, NaN is a number that is not a legal number. The Number. isNaN() method returns true if the value is NaN , and the type is a Number.
At the point where you're trying to concatenate the values the object has not yet been created.
Also this
would not represent the object in any case. You'd use this in a constructor or an object method.
To get the result you want you'll have to do this.
var urlProps = {
searchTerm: "searchSTUFF",
baseURL: "https://en.wikipedia.org/w/api.php?action=query&prop=extracts&format=json&exsentences=1&exlimit=10&exintro=&explaintext=&titles=%20&generator=search&gsrsearch=",
tailURL: "&rawcontinue=&callback=?",
finalURL: this.baseURL + this.searchTerm + this.tailURL
}
urlProps.finalURL = urlProps.baseURL + urlProps.searchTerm + urlProps.tailURL;
I would suggest using function
var urlProps = {
searchTerm: "searchSTUFF",
baseURL: "https://en.wikipedia.org/w/api.php?action=query&prop=extracts&format=json&exsentences=1&exlimit=10&exintro=&explaintext=&titles=%20&generator=search&gsrsearch=",
tailURL: "&rawcontinue=&callback=?",
finalURL: function() { return this.baseURL + this.searchTerm + this.tailURL; }
}
console.log(urlProps.finalURL());
//https://en.wikipedia.org/w/api.php?action=query&prop=extracts&format=json&e…=&titles=%20&generator=search&gsrsearch=searchSTUFF&rawcontinue=&callback=?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With