Recently, I challenged myself with a simple coding exercise to reverse a string:
function FirstReverse(str) {
var newStr;
for (var i = str.length - 1; i >= 0; i--) {
console.log(str.charAt(i));
var newStr = newStr + str.charAt(i);
}
return newStr;
}
console.log(FirstReverse("hey"));
The output turned out to be undefinedyeh
instead of just yeh
. However, when I made the change from var newStr
to var newStr = '';
, it started working perfectly.
I was curious about what data type JavaScript assumed newStr
was before adding the empty string assignment.