Split each time? (Make a Person Challenge)

The code below does not satisfy the last two requirements of the challenge:

bob.getFirstName() should return “Haskell” after bob.setFullName("Haskell Curry") .

bob.getLastName() should return “Curry” after bob.setFullName("Haskell Curry")

The solution provided does the same thing my code does except they store firstAndLast in fullName then split fullName each time they need to rather than doing it once in the variable. Clearly this affects the results but I’m not sure why:


var Person = function(firstAndLast) {

  let fullName = firstAndLast.split(" ")

  this.getFullName = function () {
    return firstAndLast
  }

  this.getFirstName = function() {
    return fullName[0];
  };

  this.getLastName = function() {
    return fullName[1];
  };

  this.setFirstName = function(name) {
    firstAndLast = name + " " + fullName[1];
  };

  this.setLastName = function(name) {
    firstAndLast = fullName[0] + " " + name;
  };


  this.setFullName = function(name) {
    firstAndLast = name;
  };
  
};

var bob = new Person('Bob Ross');


Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/make-a-person

  this.setFullName = function(name) {
    firstAndLast = name;
  };

When someone calls your setFullName function, you are not modifying fullName, but fullName is the variable that your getter functions are using.

1 Like

I had the function as { fullName = name; } before and got the same results, with one more requirement not met:

bob.getFullName() should return “Haskell Curry” after bob.setFullName("Haskell Curry") .

I agree that is the way to do it but for some reason it seems to like that way even less

If you just set fullName to name, then when bob.setFullName('Haskell Curry') is called, fullName will be “Haskell Curry”. In that case, what will getFirstName and getLastName return?

They would return Bob Ross and Bob. I see what you’re saying now. If the variable I’m modifying is different from the one i reference in the getters, after Haskell Curry is called the functions’ returns won’t be consistent with the change. Thanks for your help.

If fullName is “Haskell Curry” and getFirstName returns fullName[0] then it will return “H” and getLastName will return fullName[1] which is “a”.