Search code examples
javascriptdestructuring

Why the code returning an array with a single letter instead of whole name?


Learning Destructuring assignment in Javascript and when trying to have an array in object destructuring, just first letter return to console, why it’s happening?

function splitter(name) {
  const [fName, lName] = name.split(" ");
  return { fName, lName };
}

const {fName: [firstWord],lName} = splitter("John Doe");

console.log(splitter("John Doe"));
console.log({fName: [firstWord],lName});

console.log(firstWord);
console.log(lName);

An image of code showing an object containing elements for fname and lname as in:   object { fName: "John", lName: "Doe"}


Solution

  • This happen because splitter returns you fName and lName, each of them is a word, string, which is an array of characters.

    When you restructure fName to an array, it gives you the first letter in the array.

    If you will add more args to the array you will get the rest of the letters.

    To fix your issue just don't restructure into an array.

    function splitter(name) {
      const [fName, lName] = name.split(" ");
      return { fName, lName };
    }
    
    const {fName: [ch1,ch2,ch3,ch4],lName} = splitter("John Doe");
    
    console.log({fName: [ch1,ch2,ch3,ch4],lName});
    
    const {fName: [char1, ...restOfChars]} = splitter("John Doe");
    console.log(char1);
    console.log(restOfChars);
    
    const {fName: wholeWord} = splitter("John Doe");
    console.log(wholeWord);