简体   繁体   中英

Beginner Variable Declaration - JavaScript

I'm playing around with this easy coding challenge 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 result became undefinedyeh instead of just yeh . But , when I changed var newStr to var newStr = ''; , it suddenly worked.

What data type did JavaScript think newStr was until I assigned it to a blank string?

If you don't initialize the variable, it starts as undefined (as you probably already figured out from the result).

A variable that has not been assigned a value is of type undefined . A method or statement also returns undefined if the variable that is being evaluated does not have an assigned value. A function returns undefined if a value was not returned.

What data type did JavaScript think newStr was until I assigned it to a blank string?

var myVar; simply declares the variable, but does not assign an initial value. The value for anything not explicitly assigned a value is undefined .

Since your loop is self assigning newStr ( newStr = newStr + str.charAt(i); ) the first iteration will try to concatenate undefined to itself, which in conjunction with the concatenation operand ( + ) will coerce undefined to "undefined" .

If you do not set a value when you initialize a variable, it is set as undefined .

I think it is quite advised to set a 'default value' for each initialized variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM