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?

    1 answer 1

    You need to initialize the variable before using it.

     var normalizedHashtags = ""; 

    the value that is read during the string concatenation operation must always be initialized. You can not initialize variables (in other cases), then the variable will take the value undefined .

    • And if the variable will represent an array? What happens if I, for example, do not initialize a variable when I declare it, but then I want to put an array of integer values ​​or strings into it? What happens to this undefined? - Oriant
    • need to be initialized, otherwise it will be undefined . - Roman C