Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenating the values of an object's properties returns NaN (Javascript)

Tags:

javascript

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?

like image 385
Chirpizard Avatar asked Dec 14 '15 03:12

Chirpizard


People also ask

Why does JavaScript return NaN?

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.

What is NaN property?

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.

Is NaN a data type in JavaScript?

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.


2 Answers

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;
like image 138
Musa Avatar answered Oct 06 '22 02:10

Musa


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=?
like image 22
zjk Avatar answered Oct 06 '22 04:10

zjk