javascript

Trying to understand this short function


I don't think I'm fully grasping how this works (I'm a little embarrassed...by a little I mean a lot). Basically this is supposed to create a prompt and write console.log fullName with the first two letters in each prompt to be capitalized and concatenate together. Please help!

var fullName = ""; 
//Why does fullName have to be defined as a string? and when it's removed it doubles the value?

var name; 
var firstLetter;

var fixName = function () { 
    firstLetter = name.substring(0, 1); 
    name = firstLetter.toUpperCase() + name.substring(1);

    fullName = fullName + " " + name; 
    //what exactly is happening here under the fullName variable? What value is passing into fullName after it's being called? 
}

name = prompt("Enter your first name (all in lower case):"); 

fixName();

name = prompt("Enter your second name (all in lower case):"); 

fixName();

console.log("And your fullname is:" + fullName);

Solution

  • Here's an annotated version of the function:

    var fixName = function () { 
        // get the first letter of the string
        firstLetter = name.substring(0, 1); 
    
        // assign back to name the uppercased version of the first letter 
        // with the rest of the name
        name = firstLetter.toUpperCase() + name.substring(1);
    
        // add name onto the end of fullName
        // this will accumulate each time this function is called because
        // fullname is a global variable so it will get longer and longer each time
        // with more and more names in it
        fullName = fullName + " " + name; 
    }
    

    FYI, this is pretty horrible code overall. It should be using at least some local variables and a function argument like this:

    var fullName = ""; 
    
    function fixName(name) { 
        var firstLetter = name.substring(0, 1); 
        fullName = fullName + " " + firstLetter.toUpperCase() + name.substring(1); 
    }
    
    fixName(prompt("Enter your first name (all in lower case):"));
    fixName(prompt("Enter your second name (all in lower case):")); 
    console.log("And your fullname is:" + fullName);
    

    It probably shouldn't be modifying a global variable as a side effect either (probably should use a return value), but I didn't change that.