Why is it that I have to define a javascript string variable before using the concat() method on it? In the code below the console prints nothing. But if I initialize the variable string like this var string = ""; it concatenates like it should and prints the string in the console. This confuses me because I thought that javascript has automatic type casting, so var string; should initialize the variable, then when concat() is used on it, it should automatically change the type to "String" and concatenate?
var select = document.getElementById("CK_Expertise");
options = select.getElementsByTagName('option');
var string;
for (var i=options.length; i--;){
if(options[i].selected){
string = string.concat(options[i].value + "<br/>");
}
}
console.log(string);
Thank you - Chris
.concat()is not generally recommended for use on strings: you can and should concatenate with the+or+=operators..concat()is quite a lot slower than+. Also because it is not commonly used it makes code that does use it a bit harder to read: most JS programmers would expect to see+or+=.