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

Viewed 100

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"}

2 Answers

Let's first take the simple case, where you are just destructuring the array

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

const { fName, lName } = splitter('John Doe');
console.log(fName); // John

Remember the strings are iterable in JS

const str = 'John';

for (let c of str) {  // For-of can only be used in iterables
  console.log(c);
}

So when you do

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

then this means you are also destructuring from the fName string, which will result in the firstChar as

So the above is exactly same as:

const { fName, lName } = splitter('John Doe');
const [firstChar] = fName;
console.log(firstChar);

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

const { fName, lName } = splitter('John Doe');
const [firstChar] = fName;
console.log(firstChar);

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);

Related