Recently, I began to study JS and encountered behavior in a function that I do not quite understand. As a parameter, the function takes an array of hashtags, among which it searches for unique ones, and then returns a list of such hashtags as a string (the hashtags are commas).
const separator = ", "; function normalizeHashtags(hashtags) { var uniqueValues = hashtags.filter(function(item, pos) { return hashtags.indexOf(item) == pos; }); var normalizedHashtags; for(var i = 0; i < uniqueValues.length; i++){ if(i == uniqueValues.length - 1){ normalizedHashtags += uniqueValues[i]; } else{ normalizedHashtags += uniqueValues[i] + separator; } } return normalizedHashtags; }
The value of the returned string should look like this: tag1, tag2, tag3 . But, instead I got undefinedtag1, tag2, tag3 .
Through trial and error, I found that if the string is var normalizedHashtags; change to var normalizedHashtags = ""; then you can get the desired result. Do I need to always act in this way and constantly initialize variables when they are declared in JS?