Search code examples
javascriptarraysdata-structureslogic

Arrays output not giving proper result in JS


Here, I have created an array that will print the output, but the second output did not give a valid result, like I work as a Web Dev in Ind. I want, but it prints I work as a Sam in 27. So, what do I need to change about this program? 

const arr = [
  (name, age) => {
    console.log(`My name is ${name} and I am ${age} years old.`);
  },
  (job, city) => {
    console.log(`I work as a ${job} in ${city}.`);
  }
];

for (let i = 0; i < arr.length; i++) {
  arr[i]("Sam", 27, "Web Dev", "Ind");
}


Solution

  • To get something like the effect you want, you can use destructuring:

    const arr = [
      ({name, age}) => {
        console.log(`My name is ${name} and I am ${age} years old.`);
      },
      ({job, city}) => {
        console.log(`I work as a ${job} in ${city}.`);
      }
    ];
    
    for (let i = 0; i < arr.length; i++) {
      arr[i]({ name: "Sam", age: 27, job: "Web Dev", city: "Ind"});
    }

    Destructuring allows each function to decide which properties to pluck out of the passed object. You could add another function:

    const arr = [
      ({name, age}) => {
        console.log(`My name is ${name} and I am ${age} years old.`);
      },
      ({job, city}) => {
        console.log(`I work as a ${job} in ${city}.`);
      },
      ({city, age}) => {
        console.log(`At ${age} years old, I find ${city} to be a lot of fun.`);
      }
    ];
    
    for (let i = 0; i < arr.length; i++) {
      arr[i]({ name: "Sam", age: 27, job: "Web Dev", city: "Ind"});
    }